2016-10-23 22 views
-1

私は、キーが押されるたびに新しい値でヘルスバーを再描画するように設計された、オンラインで見つかった簡単なスクリプトを使って作業しています。ここでUnity ScriptのC#Null参照例外

はスクリプトです:

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()'メソッドを呼び出すと、null参照例外が返されます – Icepickle

+0

'= new Stat()'を試しましたが動作しません。 – Nic

+3

'あなたは 'new'キーワードを使ってMonoBehaviourを作成しようとしています。これは許可されていません。 MonoBehavioursは、AddComponent()を使用してのみ追加できます。 .ctor() BarScript::.ctor() スタット:.ctor() プレーヤー:また、あなたのスクリプトは、すべての でUnityEngine.MonoBehaviourはScriptableObjectあるいは全く基本クラスから継承することができ.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(ipress w){ 
if(for the healthbar){ 

} 
} 

よう もし何かの内側に再びif文を実行します。 助けてくれるといいです