我有一个名为Player_Data的类,其中包含一个单例,该单例允许其他类轻松访问我的类中的Data,它们能够访问除数组以外的每个变量,尽管数组在创建过程中已初始化但始终返回空引用。单身人士。我在这里错过了关键代码吗?
我曾尝试在数组IE的初始化之前放置一个This / instance指示器:
this.current_equipment[] / instance.current_equipment[]
唯一不合理的解决方案是在player_Data类之外初始化数组
IE: player_Data.instance.current_Equipment[i] = new equipment();
//This is the code that runs first, everything in this class runs just fine
public class Player_Data
{
public static Player_Data instance;
//This is called from another method at the start of the application
public void Start()
{
if (instance != null)
{
Debug.Log("ERROR: MULTPILE INSTANCES OF Player OBJECT DETECTED");
}
instance = this;
for (int i = 0; i < System.Enum.GetNames(typeof(EquipmentSlot)).Length; i++)
{
currentEquipment[i] = new Equipment();
//This correctly returns the value, no errors
Debug.Log(currentEquipment[i]);
}
}
}
//As soon as I try to Access the singleton through another class, I get the null Reference
public class Equipment_Manager : MonoBehaviour
{
private void Start()
{
Debug.Log(Player_Data.instance.currentEquipment[1]);
}
}
这是通过运行此代码获得的错误
错误:
NullReferenceException:对象引用未设置为对象的实例 Equipment_Manager.Start()(位于Assets / Code / Equipment_Manager.cs:41)
在此处链接到调试器映像 https://imgur.com/a/KSmovt2