Getting position of the right GameObject using it's script.

Hello guys,

I have a little issue in C#. I am trying to find the right Waypoint in the level. The waypoint has a script containing an int to identify itself:

public class WaypointScript : MonoBehaviour {
   public int WaypointID = 0;

// This int is declared manually from the inspector.
}

Another script containing a function to select a random waypoint to go for the NPC:

public class ArtificialIntelligence : MonoBehaviour {

	private int WaypointNumber;
	private Vector3 NewDestination;


	void SetNewDestination (){
				AllWaypoints = GameObject.FindGameObjectsWithTag ("Waypoint");
				for(var i = 0; i < AllWaypoints.Length; i++){
					WaypointNumber = Random.Range(0, AllWaypoints*);*
  •  		}*
    

}
What I want to happen now is that the script creates a Vector3 containing the transform.position of the GameObject that has the ‘WaypointID’ which is equal to the variable ‘WaypointNumber’. I guess I need to use something like a ‘while’ loop, but I don’t exactly know what the loop should look like.
I’d be awesome if someone could help me solving this riddle.

1 Answer

1

You don’t need the existing for loop. If you do the following a number will be assigned to WaypointNumber.

WaypointNumber = Random.Range(0, AllWaypoints.Length);

And then:

NewDestination = AllWaypoints[WaypointNumber];

As AllWaypoints is a GameObject array and NewDestination is a Vector3 you are missing the access to its position. NewDestination = AllWaypoints[WaypointNumber].transform.position; The first part is absolutely correct.

It works perfectly! Thanks guys!!