我試圖從魔杖射出光線,並且在運行遊戲時不斷收到此錯誤。燈仍然出來,但錯誤出現在控制檯中。我創建了一個預製燈,並將其拖到我的腳本「Light_Spell」上。下面是代碼:Unity NullReferenceException錯誤
using UnityEngine;
using System.Collections;
public class Light_Spell : MonoBehaviour {
//public Light currentSpellLight;
private ChangeSpell changespell;
private int selectedSpellNum;
private bool isSelectedSpell;
private Light wandLight;
private bool triggerIsPressed;
private float life = 1.0f;
private float speed = 15.0f;
private float timeToDie = 1.0f;
[SerializeField]
public Light lightProjectile;
// Find the light object and disable it
void Start() {
isSelectedSpell = true;
wandLight = GameObject.Find ("Spell_Light").light;
wandLight.enabled = false;
triggerIsPressed = false;
}
// Handles button presses etc
void Update() {
//changespell = currentSpellLight.GetComponent<changespell>();
if(changespell == null)
Debug.Log("error");
//Gets the currently selected spell number
selectedSpellNum = changespell.GetSelectedSpellNumber();
//Sets whether it is the selected spell
if(selectedSpellNum == 3)
isSelectedSpell = true;
else
isSelectedSpell = false;
//What happens when trigger is pressed
if (isSelectedSpell && SixenseInput.Controllers [0].Trigger != 0) {
Debug.Log("Light spell");
triggerIsPressed = true;
wandLight.enabled = true;
wandLight.intensity = (float)(SixenseInput.Controllers [0].Trigger) * 3;
wandLight.range = (float)(SixenseInput.Controllers[0].Trigger) * 5;
}
else {
triggerIsPressed = false;
wandLight.enabled = false;
}
//What happens when bumper is pressed
if (isSelectedSpell && SixenseInput.Controllers [0].GetButtonDown (SixenseButtons.BUMPER) && triggerIsPressed == false) {
Debug.Log("Light spell");
var instantiateProjectile = Instantiate(lightProjectile, transform.position, transform.rotation) as Light;
//instantiateProjectile.transform.TransformDirection(new Vector3(5,5,5));
}
}
//When bumper button is pressed, the light flashes briefly
private void LightBurst(){
wandLight.intensity = 1;
}
private void LightBurstActivated(){
timeToDie = Time.time + life;
transform.position = Camera.main.transform.position;
transform.rotation = Camera.main.transform.rotation;
}
private void DeactivateLightBurst(){
this.gameObject.SetActive(false);
}
private void LightBurstCountdown(){
if(timeToDie < Time.time)
DeactivateLightBurst();
}
private void MoveLight(){
Vector3 velocity = speed * Time.deltaTime * transform.forward;
transform.Translate(velocity * 3);
}
}
我得到的錯誤是:
NullReferenceException: Object reference not set to an instance of an object
Light_Spell.Update() (at Assets/Scripts/Spells/Light_Spell.cs:39)
感謝所有幫助
可能的重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-fix-它) – LearnCocos2D