2016-04-03 74 views
0

Picture of Error從菜單場景轉到遊戲場景後。變量已分配,但值爲空

Picture of Script

我試圖在從菜單到遊戲場景轉換到加載玩家的位置,但我得到一個錯誤,說我變,球員爲空。我已經在開始和更新函數中打印了我的變量,玩家的值,並且他們都說這個玩家有一個值,但是當我嘗試從Game場景的loadPosition函數中訪問它時,它給了我一個錯誤,表示該玩家一片空白。經過數小時的思考之後,我覺得變量播放器爲空的原因是因爲我正在從菜單場景調用toWorld()而不是Game場景。是否有任何方法在我之前從不同場景調用啓動函數轉換到遊戲場景。這個錯誤一直讓我瘋狂!爲了便於閱讀,我刪除了代碼中不相關的部分。順便說一句,Demo是我的遊戲場景。先謝謝你!

GameObject player; 


    void Update(){ 

    if (Application.loadedLevelName == "Demo") { 
    savePosition(); 
    print(player); 
    } 
} 

void Start() { 
    if (Application.loadedLevelName == "Demo"){ 
     player = GameObject.FindWithTag ("Player"); 
     print (player); 
    } 

} 

public void loadPosition(){ 

    float playerX = PlayerPrefs.GetFloat ("PlayerX"); 
    float playerY = PlayerPrefs.GetFloat ("PlayerY"); 
    float playerZ = PlayerPrefs.GetFloat ("PlayerZ"); 
    player.transform.position = new Vector3 (playerX, playerY, playerZ); 

} 


public void savePosition(){ 


    PlayerPrefs.SetFloat ("PlayerX", player.transform.position.x); 
    PlayerPrefs.SetFloat ("PlayerY", player.transform.position.y); 
    PlayerPrefs.SetFloat ("PlayerZ", player.transform.position.z); 
    float playerX = PlayerPrefs.GetFloat ("PlayerX"); 
    float playerY = PlayerPrefs.GetFloat ("PlayerY"); 
    float playerZ = PlayerPrefs.GetFloat ("PlayerZ"); 
    print (new Vector3 (playerX, playerY, playerZ)); 
} 
+0

我想到的,包括尋找玩家應該工作了'OnLevelWasLoaded'功能。 –

+0

@GunnarB。我在OnLevelWasLoaded函數中嘗試使用GameObject.FindWithTag(「Player」),Unity仍然給我錯誤。 :/ –

+0

爲了調試,使播放器成爲公衆,並在運行時查看檢查器。 –

回答

0

playernull因爲

player = GameObject.FindWithTag ("Player");

很可能失敗。確保你的GameObject的標籤是「Player」。如果標籤不是「玩家」,那麼FindWithTag將失敗。如果這種情況繼續發生,請在編輯器中將該GameObject重命名爲「Player」。

那就試試這個:

player = GameObject.Find("Player"); 

這應該解決的問題爲空。

編輯:

toWorld()功能刪除loadPosition()並把它GameObject.Find("Ethan")後的OnLevelWasLoaded()功能和之前print(player)

+0

我的標籤是「玩家」。我猜這個player = GameObject.FindWithTag(「Player」);失敗了。 –

+0

即使使用了GameObject.Find(「Player」),錯誤仍然存​​在。 –

+0

是的,重命名它然後使用GameObject.Find()。這是FindWithTag在本月出現此問題的第二個問題。 FindWithTag可能存在一個錯誤。 – Programmer