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

编者注

一直理解错了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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值