Editor’s note
I always misunderstood the object injection of unity. I thought it would be successful if I specified the object bound by the script in component, but I found that this was a wrong understanding
Unity error – nullreferenceexception
Error code
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));
}
}
Error report
NullReferenceException: Object reference not set to an instance of an object
Problem understanding
Objects created in GameObject’s scene are not bound to code objects. Confirm that GameObject cannot be bound through component
Find the content of official documents through inquiry
To get GameObject object, you must use GameObject. Find
or related functions. You cannot use other methods
Solution code
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));
}
}