【问题标题】:Unity: NullReferenceException: Object reference not set to an instance of an objectUnity:NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2019-01-28 19:16:04
【问题描述】:

我正在学习 Unity 教程。尝试检测游戏中的碰撞时遇到问题。这是错误:

NullReferenceException:对象引用未设置为对象的实例

这是脚本:

using UnityEngine;

public class Collide : MonoBehaviour
{
    public Movement movement;     // A reference to our PlayerMovement script

    // This function runs when we hit another object.
    // We get information about the collision and call it "collisionInfo".
    void OnCollisionEnter(Collision collisionInfo)
    {
        // We check if the object we collided with has a tag called "Obstacle".
        if (collisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;   // Disable the players movement.
            Debug.Log("Coollision occured");
        }
    }
}

【问题讨论】:

  • 你在哪个变量上得到这个空引用?我可以看到 2 个可能的问题,但我们不知道实际错误在哪里。
  • 您未能为检查器中的序列化字段movement 赋值。因此,当您尝试访问其成员时,它始终为 null。
  • 是的,谢谢 Serlite,我解决了这个问题。

标签: unity3d


【解决方案1】:

正如我在第二张图片中看到的那样,您没有将运动引用添加到运动场。同样在脚本中,您也没有分配参考。尝试在编辑器中分配,或者您可以创建对象。

【讨论】:

    【解决方案2】:

    原因是您没有在 Collide 组件中设置移动字段。 您可以从 Unity 编辑器中添加它,也可以在 Collide 的 Start 函数中添加以下行:

    void Start()
    {
        movement = GetComponent<Movement>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      相关资源
      最近更新 更多