我正在使用一個我在網上找到的簡單腳本,該腳本旨在每次按下某個鍵時都會用一個新值重新繪製健康欄。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)
是否有人知道如何解決這一問題?根據腳本發佈者的說法,這個代碼應該沒有任何修改即可使用。
你似乎並沒有真正構建你的「健康」成員。在一個空對象上調用'Initialize()'方法仍然會拋出一個空引用異常 – Icepickle
我試過'= new Stat()',它不起作用。 – Nic
'您試圖使用'new'關鍵字創建MonoBehaviour。這是不允許的。 MonoBehaviours只能使用AddComponent()添加。另外,你的腳本可以從個ScriptableObject或根本 UnityEngine.MonoBehaviour沒有基類繼承:.ctor() BarScript:.ctor() 統計:.ctor() 球員:.ctor() ' – Nic