2016-10-23 32 views
-1

我正在使用一個我在網上找到的簡單腳本,該腳本旨在每次按下某個鍵時都會用一個新值重新繪製健康欄。Unity腳本中的C#空引用異常

下面是腳本:

using UnityEngine; 
using System.Collections; 

public class Player : MonoBehaviour { 

    public Stat health; 

    public void Awake() 
    { 
     //Initializes the stats 
     health.Initialize(); 
    } 

    // Update is called once per frame 
    public void Update() 
    { 
     //Demonstrates the usage of each bar 
     //Takes the stats and reduces or increases it for demonstration 
     if (Input.GetKeyDown(KeyCode.W)) 
     { 
      health.CurrentValue += 10; 
     } 
     if (Input.GetKeyDown(KeyCode.Q)) 
     { 
      health.CurrentValue -= 10; 
     } 
    } 
} 

當我運行此我得到一個異常...

NullReferenceException: Object reference not set to an instance of an object 
Player.Awake() (at Assets/Scripts/Player.cs:11) 

是否有人知道如何解決這一問題?根據腳本發佈者的說法,這個代碼應該沒有任何修改即可使用。

+3

你似乎並沒有真正構建你的「健康」成員。在一個空對象上調用'Initialize()'方法仍然會拋出一個空引用異常 – Icepickle

+0

我試過'= new Stat()',它不起作用。 – Nic

+3

'您試圖使用'new'關鍵字創建MonoBehaviour。這是不允許的。 MonoBehaviours只能使用AddComponent()添加。另外,你的腳本可以從個ScriptableObject或根本 UnityEngine.MonoBehaviour沒有基類繼承:.ctor() BarScript:.ctor() 統計:.ctor() 球員:.ctor() ' – Nic

回答

0

你爲什麼不訪問你的健康欄的GameObject。它是這樣的。

using UnityEngine; 
using UnityEngine.UI; 
using System.Collections; 

public class OxygenTank : MonoBehaviour { 

public Slider oxygenTank; 
public int deductor; 
// Use this for initialization 
void Start() { 
    oxygenTank.value = 100; 
    StartCoroutine (Countdown()); 
} 

// Update is called once per frame 
void Update(){ 
    if (GameObject.Find ("Timer").GetComponent<time>().timer == 40f) { 
     oxygenTank.value = 90; 
    } 
    else if(GameObject.Find("Timer").GetComponent<time>().timer == 30f){ 
     oxygenTank.value = 80; 
    } 
    else if(GameObject.Find("Timer").GetComponent<time>().timer == 20f){ 
     oxygenTank.value = 70; 
    } 
} 

IEnumerator Countdown(){ 
    yield return new WaitForSeconds (10); 
    while (true) { 
     oxygenTank.value -= 10; 
     yield return new WaitForSeconds (5); 
    } 
} 
} 

所以你的情況只是做一個if語句再次,如果 像這樣

if(ipress w){ 
if(for the healthbar){ 

} 
} 

我使用的滑塊我的氧氣的可視化內。 希望有幫助