Reputation: 543
I have a NavAgent that is supposed to randomly run from one target location to the next. Here is my current code.
public Transform target1;
public Transform target2;
NavMeshAgent agent;
Vector3 destinationLoc;
// Use this for initialization
void Start () {
destinationLoc = target1.position;
agent = GetComponent<NavMeshAgent> ();
}
// Update is called once per frame
void Update () {
agent.SetDestination (destinationLoc);
Debug.Log (agent.remainingDistance);
if (agent.remainingDistance <= 1.0) {
Debug.Log ("It gets here.");
if (Random.Range(1,3) == 1) {
destinationLoc = target1.position;
Debug.Log ("Changed to 1.");
} else {
destinationLoc = target2.position;
Debug.Log("Changed to 2");
}
}
}
Right now it only switches between two locations but it will eventually be more. Any thoughts on why this code is not working?
Upvotes: 0
Views: 427
Reputation: 48139
I think you may be doing an overkill on setting the destination. I would set it up once in the Start() and again only once it has reached its destination. As for the Random.Range(1,3), may be a complete coincidence. You are getting an integer of 3 possibilities and it is returning 1. Try putting into a var, showing the log and adjust from there. Try expanding the range to 30 (for testing)
void Start () {
destinationLoc = target1.position;
agent = GetComponent<NavMeshAgent> ();
agent.SetDestination (destinationLoc);
}
// Update is called once per frame
void Update () {
Debug.Log (agent.remainingDistance);
if (agent.remainingDistance <= 1.0) {
Debug.Log ("It gets here.");
int rr = Random.Range(1,30);
Debug.Log( "Random value: " + rr );
if (rr == 1) {
destinationLoc = target1.position;
Debug.Log ("Changed to 1.");
} else {
destinationLoc = target2.position;
Debug.Log("Changed to 2");
}
// Set destination AFTER it has been changed
agent.SetDestination (destinationLoc);
}
}
Additionally, you might get a better and faster response by going to the sister site of
https://gamedev.stackexchange.com/
Upvotes: 1