So, I’m slowly making my way through the RPG course, and in between following those lessons, I’m working on things I want to include in my game.
Right now, I’m working on wildlife, in this case a rabbit. I’m creating a rudimentary AI for it.
So what I need it to do is get the location of all objects in the scene with a certain tag, then go to the nearest one. In game terms, It’s going to the nearest source of food, which happens to be an object with the tag bush.
The problem I’m having is sorting which one is closest.
The code I’m using for this is these three lines:
Vector3.Distance(myTransform.position, pos); //get my position
food = GameObject.FindGameObjectsWithTag(“bush”); // get all food objects
Vector3 pos = food[0].GetComponent().position; // determine position of object
Vector3.Distance(myTransform.position, pos); // determine distance
What I can not figure out how to do is sort the returned game objects by distance. I know it’ll involve a loop, but my problem is the lack of Arrays.
In PHP, I would create an associative array and sort it by the distance key, but how do I do that in Unity?
Thanks.