是什么导致使用 NavMeshAgent 的光线投射单击移动脚本返回 NullReferenceException?

What is causing this raycast click movement script using NavMeshAgent return a NullReferenceException?

提问人:Tristan Littlewood 提问时间:1/11/2023 最后编辑:Tristan Littlewood 更新时间:1/11/2023 访问量:58

问:

当我运行从教程中复制的这个脚本时,Unity 控制台始终返回 NullReferenceException: Object reference not set to an instance of an object。当我右键单击以指示对象移动时,就会发生这种情况。我已确保该对象具有NavMeshAgent组件,但引擎找不到它。

澄清一下,我不是在问什么是 NullReferenceException。我在问为什么这个脚本返回一个,尽管我给了它一个要引用的对象并且该对象不为空。从本质上讲,我正在寻找确定为什么引用会找到 Null,而它应该找到 NavMeshAgent 组件。

NavMeshAgent is a component on the Object that the script is attached to.

`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class CharacterMovement : MonoBehaviour
{

    NavMeshAgent agent;

    public float rotateSpeedMovement;
    float rotateVelocity;

    // Start is called before the first frame update
    void Start()
    {
        agent = gameObject.GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        //When pressing RMB
        if(Input.GetMouseButtonDown(1)){
            RaycastHit hit;
        
            //Checking if raycast has hit the navmesh system
            if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit,
            Mathf.Infinity)){

                //have the player move to the point
                agent.SetDestination(hit.point);

                //ROTATION
                Quaternion rotationToLookAt = Quaternion.LookRotation(hit.point - 
                transform.position);
                float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y,
                rotationToLookAt.eulerAngles.y,
                ref rotateVelocity,
                rotateSpeedMovement * (Time.deltaTime * 5));

                transform.eulerAngles = new Vector3 (0,rotationY,0);
        
                }
            }
        }
    }`

对象应移动到单击的点,但不会。我尝试使用序列化字段并使用

this.gameObject.GetComponent<NavMeshAgent>();

但无论如何,我都会遇到同样的错误。

C# unity-game-engine nullreferenceexception 导航网格

评论

0赞 BugFinder 1/11/2023
错误中指示了哪一行?我的一部分会猜到camera.main吗?
0赞 Tristan Littlewood 1/11/2023
@BugFinder表示线路代理 = gameObject.getComponent...如果我通过单击错误消息打开脚本。

答:

0赞 Chuck 1/11/2023 #1

你说错误:

表示线路代理 = gameObject.getComponent...如果我通过单击错误消息打开脚本。

但我认为这根本不是那条线,因为不应该抛出异常,如果组件不存在,它只会返回。gameObject.GetComponent<>()null

我怀疑您在其他游戏对象上获得了脚本,而其他游戏对象没有附加的 NavMeshAgent。

此处的简单故障排除步骤可验证:

void Start()
{
    agent = gameObject.GetComponent<NavMeshAgent>();
    if(agent == null)
    {
        Debug.LogErrorFormat("Failed to find a NavMeshAgent on {0}!", gameObject.name);
    }
}

然后看看缺少 NavMeshAgent 的东西的名称是什么。我敢打赌这不是你想的那样!

评论

0赞 Tristan Littlewood 1/11/2023
似乎不是这样,但很好验证。当我运行时,它不会输出那行。更新了帖子以澄清,因为我忘记包含它,但是单击RMB时会调用错误。
0赞 Chuck 1/11/2023
@TristanLittlewood,如果你没有在那里得到一个调试语句,那么你有一个有效的NavMeshAgent,你的NullReferenceException在其他地方。不过,你已经告诉我们这是这条线,但事实似乎并非如此。
1赞 ephb 1/11/2023 #2

脚本中只有两个变量可能导致 NullReferenceException。

您的类定义了一个变量,该变量可以是 或 。 由于其他注释已排除为 null,因此您可能没有在相机上设置 MainCamera 标记,因此会导致异常。agentCamera.mainagentCamera.main

如果不是这种情况,则应使用 try/catch 包装 if 语句的内容,以标识未设置的对象。agent

       if (Input.GetMouseButtonDown(1))
        {
            try
            {
                RaycastHit hit;

                //Checking if raycast has hit the navmesh system
                if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit,
                Mathf.Infinity))
                {

                    //have the player move to the point
                    agent.SetDestination(hit.point);

                    //ROTATION
                    Quaternion rotationToLookAt = Quaternion.LookRotation(hit.point -
                    transform.position);
                    float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y,
                    rotationToLookAt.eulerAngles.y,
                    ref rotateVelocity,
                    rotateSpeedMovement * (Time.deltaTime * 5));

                    transform.eulerAngles = new Vector3(0, rotationY, 0);
                    Debug.LogError("hello");

                }
            }
            catch (System.NullReferenceException exception)
            {
                Debug.LogError("This is the object causing the exception", this);
            }
        }

有关调试 NullReferenceExceptions 的进一步阅读,请查看本指南