c# - 空引用异常 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;
}
}
解决方案
这意味着null
例如,GameObject.Find(..)
如果找不到对象,则该函数中的代码中的某些内容将返回 null 。GetComponent<T>()
也可以返回null。
您需要确保找到游戏立方体,并且当前游戏对象和主立方体实际上附加了一个渲染器组件。组件也是如此GameCntrl
。
推荐阅读
- firebase - 云功能在firestore上保存不同的日期
- javascript - ReactJS 组件库的多个导出
- python - 将自定义函数应用于 pandas DataFrame 返回“DataFrame”对象不可调用
- google-tag-manager - 如何仅有时触发标签?
- c++ - 无法打印 c++ Hello World,未定义对“WinMain”的引用
- r - Caret:如何设置自定义模型 deepnet
- javascript - 尝试轮询服务器,但是由于算法中断,rxjs 方法可能不正确
- java - 使用 RJSDMX R 从 API 获取 XML 数据
- sql-update - UPDATE 语句的变量
- java - 在 JavaFX 应用程序中下载文件时出现“此应用程序没有响应”