-1

I want to make RTS game for test.But there is a error(NullReference Exception) that I face to face with every time while making click-to-move system.Here is my code:

public class Movement : MonoBehaviour {

    NavMeshAgent agent;

    // Use this for initialization
    void Start () {
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100));   //---Unity says that error is in this line!
            agent.destination = hit.point;
        }
    }
}
Ehsan Mohammadi
  • 1,168
  • 1
  • 15
  • 21
  • 2
    You use a `;` at the end of `if (Physics.Raycast(....))` statement. So `agent.destination = hit.point;` runs even `if` statement returns `false` (and `hit = null`). Just delete `;` :) – Ehsan Mohammadi Oct 06 '18 at 21:59

1 Answers1

0
NavMeshAgent agent;

// Use this for initialization
void Start () {
    agent = GetComponent<NavMeshAgent>();

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) 
        {
           agent.destination = hit.point;
        }

    }

}
Nicolás de Ory
  • 614
  • 9
  • 31