0
\$\begingroup\$

I have a 3D model of a house, and I want an autonomous robot to move from 1 object in this house to the next one. I have it moving to the first, but it won't move to the second one. This is my code:

using UnityEngine;
using System.Collections;

public class MoveTo : MonoBehaviour {

public Transform[] goals;

void Start () {
    NavMeshAgent agent = GetComponent<NavMeshAgent> ();
        agent.destination = goals[0].position;

    if (agent.transform.position == goals[0].position) {
        agent.destination = goals[1].position;
    }

}
}

I'm a complete beginner in code, please keep that in mind :)

\$\endgroup\$
1
\$\begingroup\$

The Start method is only executed once at start and the NavmeshAgent won't start moving the object before the Start method finished. The moving happens between calls to Update.

So check if you reached the destination in your Update method, not your Start method.

I would also recommend you to use agent.remainingDistance to check if the destination is reached. Comparing positions for equality is quite error-prone because even though the == operator for Vector3 is overloaded for returning true even when the positions are just almost identical, Unity's definition of close enough might be different than yours. If you want to compare positions, at least do it by checking if their distance is smaller than what you would consider close enough for "being there".

\$\endgroup\$
  • \$\begingroup\$ You, sir, are awesome! Thank you so much for your help. I got it working. I learn so much quicker by asking simple questions and working by trial and error than reading endless walls of tutorials. Thanks!! \$\endgroup\$ – juuljuup May 29 '16 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.