Unity中的“对象引用未设置为对象的实例”错误

时间:2018-10-06 20:44:46

标签: c# visual-studio unity3d

我想制作RTS游戏进行测试。但是在制作点击移动系统时,每次都会遇到一个错误(NullReference Exception)。这是我的代码:

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;
        }
    }
}

1 个答案:

答案 0 :(得分: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;
        }

    }

}