编者注
一直理解错了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));
}
}