我遇到的問題
我已經創建了一個包含靜態變數的類,我希望從中寫入和讀取資料,這是資料腳本:
本地資料容器.cs:
public class LocalRuntimeData
{
/*
Local Runtime Data is the container for all local data used during runtime.
*/
public static LocalPlayer Player;
public static AvatarInstance Avatar;
public static LocomotionManager LocomotionManager;
public static TrackedDevices TrackedDevices;
/*
Methods
*/
}
但是使用另一個腳本將資料從 'Start()' 方法保存到 'Player' 變數,然后將該資料加載回其他組件,沒有回傳任何內容 - 但我不明白的是沒有錯誤來自我的 IDE 或 Unity 編輯器。
這是試圖將資料保存到靜態“Player”變數的第二個腳本。
本地播放器.cs:
private void Start()
{
// Save player to LocalSpace runtime data.
LocalRuntimeData.Player = transform.GetComponent<LocalPlayer>();
...
我還嘗試使用LocalRuntimeData.Player = this;僅從它自己傳遞組件而不嘗試一些無用的解決方法,即圍繞變換回圈回同一個組件,但這不起作用。
問題
目前,我不知道這是否甚至將資料寫入靜態變數,因為當我嘗試使用時LocalPlayer Player = LocalRuntimeData.Player,實際上沒有任何內容回傳到試圖獲取該靜態變數的組件。
是的,嘗試訪問該靜態變數的組件正在參考我們在“LocalRuntimeData.cs”下的命名空間。提醒; 我的 IDE 或 Unity 編輯器都沒有出現錯誤。
uj5u.com熱心網友回復:
if(transform.GetComponent<LocalPlayer>() == null)
transform.AddComponent<LocalPlayer>();
LocalRuntimeData.Player = transform.GetComponent<LocalPlayer>();
uj5u.com熱心網友回復:
解決了
我的菜鳥錯誤
Unity 提供Awake()和Start()方法是有原因的。嘗試使用靜態變數執行所有操作Start()是腳本無法獲取變數的原因,因為當他們嘗試在寫入資料的同時訪問資料時,從技術上講,它不存在。只需要更改將資料寫入Awake()方法的一個腳本,以便Start()在其余組件呼叫該方法之前該變數就已存在。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365428.html
