首页 > 解决方案 > 空引用异常 Unity 2d

问题描述

我在 Unity 2d 中遇到问题

NullReferenceException:对象引用未设置为对象 RightOne.OnMouseDown () 的实例(在 Assets/Scripts/RightOne.cs:13)UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

这是脚本:

using UnityEngine;
using System.Collections;

public class RightOne : MonoBehaviour {

    private GameObject mainCube;

    void Start () {
        mainCube = GameObject.Find ("Main Cube");
    }

    void OnMouseDown () {
        if (GetComponent <Renderer> ().material.color == mainCube.GetComponent <Renderer> ().material.color)
            mainCube.GetComponent <GameCntrl> ().next = true;
        else
            mainCube.GetComponent <GameCntrl> ().lose = true;
    }
}

标签: c#unity3d

解决方案


这意味着null例如,GameObject.Find(..)如果找不到对象,则该函数中的代码中的某些内容将返回 null 。GetComponent<T>()也可以返回null。

您需要确保找到游戏立方体,并且当前游戏对象和主立方体实际上附加了一个渲染器组件。组件也是如此GameCntrl


推荐阅读