Unity general questions

Comments

  • Hey guys,

    Quick question. I have a sprite sheet with 4 different colours of a ball. How can I tell my object to switch to another image in that sprite sheet?

    Thanks,
    Dom
  • edited
    @CiNiMoD

    Your game object has a SpriteRenderer component, so set the image there, like so...
    ball.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(string.Format("Sprites/{0}","ball1"));

    Oh hang on, a spritesheet? So you have a "multi" sprite that has been sliced by a grid? You might need to reference the specific child sprite / frame in your spritesheet...

    Example:

    filename = "ball"; //filename of your texture in Resources/Sprites...
    int child = 3; //frame number 4, 0 is first
    Sprite[] multiSprite = Resources.LoadAll<Sprite>(string.Format("Sprites/{0}",filename));
    ball.GetComponent<SpriteRenderer>().sprite = multiSprite[child] as Sprite;

    Give that a shot...
  • dislekcia said:
    You could also calculate the cross product of your surface normal and the shark's forward, then get the cross of that against the surface normal to create a surface forward, then normalise that and multiply by the length of the shark's forward.
    My brain broke reading that. Can you explain the steps?

  • Fengol said:
    dislekcia said:
    You could also calculate the cross product of your surface normal and the shark's forward, then get the cross of that against the surface normal to create a surface forward, then normalise that and multiply by the length of the shark's forward.
    My brain broke reading that. Can you explain the steps?
    Cross product of surface normal (points straight up out of surface) with the shark's forward vector (whichever way the shark is facing) will give you a vector that's perpendicular to both and pointing to the left/right of the shark, along the surface. Call that A.

    Cross product of A and surface normal will then give you a vector perpendicular to both, so it'll lie on the surface, but be "pointing" in the direction of the shark's forward vector relative to the surface, think of the "shadow" of the shark's forward vector on the surface - they'd both be pointing in the same direction. Call this B.

    The problem is that B is not guaranteed to actually be a specific magnitude after those cross products. So you have to normalise it to magnitude 1, let's call that Bn.

    Then, you have a couple of options: If you want the shark's speed to stay constant and it should move as fast as it was going before, just along the surface this time, then you multiply Bn by the length of the shark's forward movement vector (using transform.Forward will just give you 1, so use the speed of the shark itself); If you want the shark's speed relative to the surface to stay the same so that it keeps moving at the same speed along the surface, but stops moving in other directions, then you want to use the dot product of the shark's forward movement vector and Bn.

    Unfortunately I don't have the tools to draw this out right now, but if it's confusing, do that.
  • edited
    cross product of the sharks current forward vector and the surface normal creates a new vector perpendicular to both.
    if you're imagining/visualising it it'd be kinda sticking out to the side from the point where the two cross each other, this vector itself is tangent to the plane but in the wrong direction (its in the left/right direction). So we cross it with the normal again to get a vector that is perpendicular to the normal and the left/right tangent giving us a forward/backward tangent to the plane. normalizing after to get the vector length to 1 and multiply by the appropriate shark speed to get the sharks new surface skidding vector.

    on second reading this might not explain it any better but I hope it helps a bit.

    edit: dislekcia is faster and more detailed.
  • Thanks @dislekcia, I followed you easily enough :)
  • edited
    Does anyone know how expensive "SendMessage" operations are. I have used it quite a bit in a recent project without any real hit in performance. Now I want to use it a whole lot more, but don't want to experience problem in a week from now. Will I be safe by throwing these around in code willy-nilly. Any feedback will be a much appreciated.
  • From what I've read in many articles it is expensive and you should rather be using delegates.
    A great example I've used in many projects is this one:

    http://wiki.unity3d.com/index.php/CSharpMessenger

    Usage examples:

    Messenger.AddListener<GameObject>("prop collected", PropCollected);
    Messenger.Broadcast<GameObject>("prop collected", prop);

    Messenger.AddListener<float>("speed changed", SpeedChanged);
    Messenger.Broadcast<float>("speed changed", 0.5f);

    I love using this as it makes a lot of things independant.
    Thanked by 1hermantulleken
  • @dreampunchboy thanks for the examples. I will read up on delegates
  • Im having a bit of an issue. In the Start function in one of my game objects I create another game object. When the game shows for the first time the image for the created game object doesnt show. If I have a button the recreates it, it draws correctly the second time though :/ Also, this only happens on device. When I run it on my PC it works fine. Any ideas?
  • CiNiMoD said:
    Im having a bit of an issue. In the Start function in one of my game objects I create another game object. When the game shows for the first time the image for the created game object doesnt show. If I have a button the recreates it, it draws correctly the second time though :/ Also, this only happens on device. When I run it on my PC it works fine. Any ideas?
    Try with Awake() instead of Start(). Start might not be being called early enough for that first frame while stuff loads.
    Thanked by 1konman
  • dislekcia said:

    Try with Awake() instead of Start(). Start might not be being called early enough for that first frame while stuff loads.
    Awake seems to make it worse, as in, now its happening on desktop also :/
  • CiNiMoD said:
    Awake seems to make it worse, as in, now its happening on desktop also :/
    Well, now you'll have an easier time testing it ;) How are you creating the object?
  • Perhaps the best question to ask is what this object is, where it should be, how it gets there, and what's happening in its own Start/Awake. It sounds like some dependencies for its own creation are missing. Is it just a sprite? How are you positioning it?
  • In the Unity Editor you can switch to scene view, and look for your object. Also, make sure that it is actually created by checking that it is in the hierarchy list thing first
  • Has there been some recent hectic Unity updates that changed expected behaviours?

    I ask cos I made a GameObject, then duped it a couple times, then added a script to one, and then hit apply. Then went to playtest, then was utterly confused by what resulted. After a lot of wondering around, the dupes turned out to not have inherited the changes... Then I reiterated the changes on one of them and hit apply again - and still everything else was different. I had to hit revert on every single one of the dupes individually to get the changes.

    Is this normal or have I just totally not been aware of how it's supposed to work? >_<
  • edited
    As far as I know, what you describe will only work on prefabs. So if you make a prefab of your object, drop it in the scene, then dupe that, make changes and hit apply, they should come through. (As long, I think, if you have not made changes to the dupes that will override the prefab value).

    If this is not working, you may well have a Unity bug... There has been a few bad prefab bugs in the past, so it will not surprise me...
  • oh yeah I forgot to mention, yes it was a prefab, otherwise there wouldn't be an apply :)

    Couldn't duplicate the situation. Bleh :/
  • edited
    Hi guys

    Erm, embarrassing. This seems so simple but... Not so, apparently :/

    I'm trying to get a simple thing to happen - I have blocks, and I want an object to move towards a point in discreet steps, not turning directly towards it. So for example:

    [1] [2] [3]
    [4] [5] [6]

    Assume target is at [3]
    If the object is at 1, the object must move from 1 to 2, that is, face right.
    If the object is at 4, the object must move from 4 to 5, face right.
    If it's at 5, it's a toss up and it's a random choice between facing 2 and 6, or depending on if either is occupied.

    What I have are spacial coordinates of the items - so I'd like to work out the angle from the object to the target and work out its heading (0 degrees up, 90 to the right, 180 down, etc) and set it...

    I tried RotateTowards but I couldn't work out if this is right:
    Vector3.RotateTowards(transform.position, Target.transform.position, 1.57079633f, 0.0f);
    the 1.5 something is because google says 90 degrees is *that* in Radians... Well, that code doesn't work.

    transform.Lookat(Target.transform, Vector3.up) does work in that it rotates it directly to face the object, but I don't want that. I want it to turn 90 degrees based on where the target is in relation to itself, finding the "shortest" path.

    Does this make sense? XD
  • Maybe a 2-dim array to store location/occupancy ? If target is in row < me then I go up, if target in column > me then I go right?

  • Ha XD

    Everyone always says use arrays for blocks, every game I make people say that @_@ but my games aren't really discreet blocks, the characters walk between them, and I'd like to not have to write extra systems when I could just get an angle between two points... Right? Or is getting an angle between two points harder than writing an array that doesn't do anything else? XD
  • Vector maths!

    Vector3 relative = transform.InverseTransformPoint(target.position);
    float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg;
    transform.Rotate(0, angle, 0);


    That is quite literally the documentation for atan2.

    All you need to do is round angle to the nearest 90 degrees.
    Thanked by 2Tuism FanieG
  • edited
    @Squidcor thanks so much, there was NO WAY I could have figured that out on my own. Damn, that's a bunch of maths :/

    For others' benefit, here's the full thing including the rounding to the nearest 90 degrees :)

    Vector3 relative = transform.InverseTransformPoint(BuneeExit.transform.position);
    float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg;
    angle = Mathf.Round(angle / 90) * 90;
    transform.Rotate(0, angle, 0);
    Thanked by 1FanieG
  • Hi, I have a bit of a "Juice" question. I have a texture that gets drawn on the screen as a HUD element whenever a player picks up a weapon in my project. The code for this is simple:

    void OnGUI()
    	{
    		GUI.DrawTexture(new Rect(10,470, 100, 100), assignedWeapon);
    	}


    I now want to add a bit of juice to this in the form of a particle effect. I have created the particle system and want to play it at the texture's location whenever the player picks up a new weapon. So that it looks like the Icon lights up for a second. My question is this: How do I ensure that the location of the particle system is at the same spot as the the DrawTexture's position. I have attached it to the main camera in about the same spot as the texture/icon and this does work. However, if the game is played in another resolution the position may not be the same anymore. Any suggestions on how I can go about this would be much appreciated.
  • I never use GUI... I just attach things to quads attached to the main camera and manipulate them from there. Hope that helps? :)
  • @Tuism - That does sound like a solution. Do you then mess with the renderer = false/true, property to switch between different quads at the same position? Or do you change the sprite of the quads? When a new weapon is picked up I mean. At the moment I am assigning a new texture to the assignedWeapon variable when a new weapon is picked up, and then using the GUI.drawTexture to display the correct weapon. See Image below:

    image

    Hope my question makes sense.

  • Well I haven't gone that far with my UIs yet, but both of what you're proposing would work :) I guess we'll have to ask other people for what's more "optimal", cos I'm not sure about that.

    The only thing I know is that instantiating and destroying objects cost a lot more than what you're saying, probably.
    Thanked by 1FanieG
  • edited
    Tuism said:
    Ha XD

    Everyone always says use arrays for blocks, every game I make people say that @_@ but my games aren't really discreet blocks, the characters walk between them, and I'd like to not have to write extra systems when I could just get an angle between two points... Right? Or is getting an angle between two points harder than writing an array that doesn't do anything else? XD
    Proper spacial data structures are always, always, always useful.

    Want to know if something has neighbours? Look it up.
    Want to know if a space is free? Look it up.
    Want to know if there's a path from spot x to spot y? Look it up.
    Want to know if there's anything at all in a certain row or column? Look it up
    Want to know if your board is full or empty? Look it up.
    Want to find and respond to patterns or other things in board? Look it up

    All of these things become non-trivial (and significantly more expensive) if you don't have proper ways of representing your space. Now, of course, all of your requirements depend on the game you're making, but it's safe to say that 99% of the time, you'll probably make your life easier by having simple, fast ways to look up stuff in space.

    It may sound like a lot of theoretical computer science bullshit (and maybe some of it actually is), but seriously, games always need to have good ways of knowing what's going on, and stuff like this always helps. Utility always trumps theoretical computer science bullshit (as much as I like theoretical computer science bullshit), and there's tons of utility here.
  • OK thanks for that, those are good points, I'll try to incorporate them into my "engines". Though the things is that I prefer to have self-governing systems that are adaptable when prototyping (or at ones I can understand), because those are flexible while the data structures are kinda extrinsic to what the things are doing themselves...

    But yes, I think having a data structure that mirrors what's happening in the world could be a good approach :)
  • @FanieG - look at the hudtext implementation of NGUI if you can - it basically checks the object's coordinates in screen space, and uses that to display the GUI component in 2D space. It runs every frame to poll the position, but at least it still belongs to the GUI stack. I personally prefer this route, because it does not break the atomicity of the character component, and instead decouples the UI from the game objects themselves. Another benefit is also that your actual text will be crisper as UI than it would be as an object rendered in 3D space.
    Thanked by 1FanieG
  • Tuism said:
    Everyone always says use arrays for blocks, every game I make people say that...
    And you have yet to catch the subtle hints. :P
  • Tuism said:
    Everyone always says use arrays for blocks, every game I make people say that...
    And you have yet to catch the subtle hints. :P
    Because it's always slower for me, and I'm prototyping for speed :P
  • I don't know man...running into walls usually feels pretty slow to me. :P

    In all seriousness though, I think you should really put in the time to learn at least how 2D Arrays work. I know it might seem slower, but it will save you a bucket load of time in the future. It's one of the most basic data structures but has major return on investment.
  • edited
    Hi guys... There is a thing that I don't understand that seems to be... a thing.

    I have, for example, this code that I call in Update()
    if (Input.GetKeyDown(KeyCode.A))
    	{
    	beetExit.transform.position = new Vector3 (beetExit.transform.position.x + 1, beetExit.transform.position.y, 0f);
    	}


    Then, I use the exact same code, taking out out of the GetKeyDown, so like this:

    beetExit.transform.position = new Vector3 (beetExit.transform.position.x + 1, beetExit.transform.position.y, 0f);


    That happens as a part of an if/else inside a void function, so like:

    void cleanUp ()
    	{
    
    		for (int ii = 1; ii < 12; ii++)
    		{
    			if (playField[9,ii] != null)
    			{
    				playField[9,ii].transform.position = new Vector3(beetExit.transform.position.x, beetExit.transform.position.y+1, 0f);
    				playField[Mathf.RoundToInt(beetExit.transform.position.x), Mathf.RoundToInt(beetExit.transform.position.y-1)] = playField[9,ii];
    				playField[9,ii] = null;
    				beetExit.transform.position = new Vector3 (beetExit.transform.position.x + 1, beetExit.transform.position.y, 0f);
    			}
    		}
    
    	}


    I've bolded the part that is the duplicate of the code further up. Can't bold code, doh, but there is a part that is duplicate of the code further up. The rest of the code is irrelevant because I *know* that the rest of the code runs. I can see it take place. BUT that exact code doesn't have any effect when ran.

    WHY IS THAT???

    Is there some kind of object reference convention that miss objects between different functions declared with void or something? Am I missing something??? :/

    (also you'll notice this is me learning 2D arrays :P)
  • How sure are you are you that it runs? Have you tried Debug.Log to make sure (inside the if statement)? I'll just assume you have. Just yesterday something happened to my monodevelop, and changes I made in my code had no effect at all. I think it wasn't compiling to the right target or something. Had to restart to unity and MD to fix it.
  • Thanks for that! Sometimes I'm not sure if that's the case, I shut down Unity and Mono to see... I wonder WHY the heck it happens because yes I know it happens... Anyhoo...

    This isn't that :/

    OK!!! I solved it, erm one of the lines were fucking up the whole 2D array by trying to get to a field that's not there, and somehow that kicked the entire function out. WHY would it do that??? Don't get it :/
  • If it was trying to get a field that was not there, was it producing an error? If your functions produce errors, they normally just stop executing, but the main game loop carries on. So it might just appear as if nothing is happening, but actually errors are popping up.
  • Rule #1 of Unity Development: If you don't run with your Console Window visible so that you can see Red, you're doing it wrong!
  • To be honest, I do run with the Console open, and I do usually see errors... Sometimes I let them be because I know I'm making mistaken calls in for/do loops or whatever... But I never knew functions exited if it encountered any errors... I thought just the error-inflicted line wouldn't execute.

    Now I know!
    Thanked by 1Denzil
  • Tuism said:
    To be honest, I do run with the Console open, and I do usually see errors... Sometimes I let them be because I know I'm making mistaken calls in for/do loops or whatever... But I never knew functions exited if it encountered any errors... I thought just the error-inflicted line wouldn't execute.

    Now I know!
    It's also important to know that if ever you deploy builds to mobile devices (especially iOS), exceptions thrown from script like that will usually hard crash your game.

    So yeah. Don't ignore them.
    Thanked by 1Tuism
  • Hey

    So I have been having problems with addTorque for a rigidbody2D. Sometimes it adds torque other times it doesn't. There is also a force applied just before the torque. I don't know if I am doing something wrong or understanding something wrong.

    The code is just addForce then add Torque -500
  • loet said:
    Hey

    So I have been having problems with addTorque for a rigidbody2D. Sometimes it adds torque other times it doesn't. There is also a force applied just before the torque. I don't know if I am doing something wrong or understanding something wrong.

    The code is just addForce then add Torque -500
    Are you calling this in fixedUpdate (every fixed frame)?
    Other possibilities are the object may be too heavy, or drag too much, or perhaps a rigidbody setup mistake.

    (It will be helpful if you post the full code, as well as a screeny of your rigidbody setup).



  • Hey guys, time for more general unity questions! :D *gameshow fanfare*

    I have an array of AudioClips, and right now I'm populating them by manually dragging them from projects to the inspector in the editor...

    But now I'm reaching like 100 samples... So it's a heck of a drag to drag (pun intended).

    Is there a way to do a for loop to pull a pile of files into an array based on its name in projects? So... Constructing names in string "audio file name " + n (to get "audio file name 1" for example) and have that name reference something from the library to push into an array?
  • Yeah, you can. :) I imagine you'd want to use something like the Directory.GetFiles() method (which gets you an array of files' names), combined with AssetDatabase.LoadAssetAtPath() (which gets you the actual asset files).
  • edited
    What @Elyaradine suggests will only work in the editor, though. So you can use that technique to write an editor script that can populate your list for you automatically. Alternatively, you can load assets dynamically by using Resources.Load() with some path relative to a Resources/ folder in your project, which you can do at runtime.

    If you're getting into editor scripting, you can also technically write your own inspectors for the object that contains your array so that you simply drag in a whole big list of files from projects and have it populate on its own, or, in fact, do whatever the hell you want! Unity's extensible editor is a rabbit hole that goes a long, long, long way down.

    EDIT:
    Also remember that if you ARE using editor scripting to change an object in your scene or a prefab in your project, make sure to call EditorUtility.SetDirty() on it or things will behave very very strangely indeed (values will appear to change but updates will not be committed).
    Thanked by 1mattbenic
  • Editor... scripting? What is that? :/ I'm a bit lost as to what you're talking about here. Been looking at Directory.GetFiles(), starting from there... Not sure what it does yet. And googling is coming up with a bunch of very technical looking things, and I'm working through them...

    What I want to do is to... get things from the library into an array using a string construction to find names. Names will be unique. Is that... what @elyaradine is describing? XD
  • EDIT:
    Also remember that if you ARE using editor scripting to change an object in your scene or a prefab in your project, make sure to call EditorUtility.SetDirty() on it or things will behave very very strangely indeed (values will appear to change but updates will not be committed).
    Jeez, the number of times I've forgotten this one!
  • Hello hello :)

    A quick one, I haven't found anyone with even the same problem on Google, let alone a solution :/

    I use a lot of TextMeshes for my UI because, well, it seems the easiest.

    Sometimes - often - but not always - when I type text into a TextMesh so that it says thing x, it looks like that in Editor. Then when I start the game, the same text turns into that placeholder bunch of random character material texture. Without fail. If I change the text during play, viola, it's back to what it's supposed to be, then when I stop and play again, it happens again.

    It's not ALWAYS the case, some textures are fine.

    The only solution I have been able to find is to always update the text at runtime, but that takes a long time if I have a bunch of stuff on screen, so was wondering if anyone has run into this and if there's a solution for it???
  • Hey,

    So I have a quick (and Im sure, stupid) question :P

    I am trying to get the cursor position in world coordinates. Now I know how to do this with the camer.ScreenToWorldCoordinates, but on the game object I am using it says that there is no camera attached?

    Not sure if this has anything to do with it, but I am using a 2D object.
  • Are you referencing the camera via Camera.main?
    Thanked by 1Kobusvdwalt9
Sign In or Register to comment.