博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Unity - NullReferenceException: Object reference not set to an instance of an object
阅读量:6990 次
发布时间:2019-06-27

本文共 1393 字,大约阅读时间需要 4 分钟。

  hot3.png

编者注

一直理解错了Unity的对象注入,以为是在Compontent指定脚本所绑定的对象,就能够成功,但是发现这个是错误的理解。

Unity错误 - NullReferenceException

错误代码

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;public class SliderLightBehaviourScript : MonoBehaviour {	public GameObject light;	// Use this for initialization	void Start () {		//this.light = GameObject.Find ("Directional Light");	}		// Update is called once per frame	void Update () {			}	public void OnDrag(float value){		Debug.LogError (value);		this.light.transform.rotation = Quaternion.Euler (new Vector3(value,0.y,0));	}}

报错

NullReferenceException: Object reference not set to an instance of an object

问题理解

GameObject的场景内创建的对象没有绑定到代码对象上。确定通过Component无法绑定GameObject。

通过查询发现

获取GameObject对象必须通过GameObject.Find或者相关函数进行实现,无法通过其他方式。

解决代码

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;public class SliderLightBehaviourScript : MonoBehaviour {	public GameObject light;	// Use this for initialization	void Start () {		this.light = GameObject.Find ("Directional Light");	}		// Update is called once per frame	void Update () {			}	public void OnDrag(float value){		Vector3 light_rotation = light.transform.rotation.eulerAngles;		Debug.LogError (value);		this.light.transform.rotation = Quaternion.Euler (new Vector3(value,light_rotation.y,0));	}}

转载于:https://my.oschina.net/hava/blog/1546311

你可能感兴趣的文章
存储过程中执行动态Sql语句
查看>>
SQL Server里简单参数化的痛苦
查看>>
最好用的图表工具 -- ECharts
查看>>
主攻ASP.NET MVC4.0之重生:ASP.NET MVC使用JSONP
查看>>
Spark_Streaming
查看>>
【细说Java】揭开Java的main方法神秘的面纱(转)
查看>>
ArcGIS Server密码丢失
查看>>
对象模型的细节
查看>>
Mac 显示和隐藏文件
查看>>
sigaction 用法实例
查看>>
React-Router V3 如何进行页面权限管理
查看>>
虚拟无线接入网:行业的演进方向
查看>>
又一波猛料!iPhone 8启动Face ID解锁 ,还玩起了3D动画表情
查看>>
xcode高效开发必备! mark,待实践
查看>>
《Linux From Scratch》第三部分:构建LFS系统 第六章:安装基本的系统软件- 6.38. Libtool-2.4.6...
查看>>
mysql 数据类型
查看>>
【逻辑题】逃出生天~
查看>>
【数学题】概率问题之-学生的生日
查看>>
Facebook专家:Hadoop不足以处理大数据
查看>>
gcc常用命令
查看>>