2017-05-10 93 views
0

當我向玩家詢問他/她的名字時,我有第一個場景,並且我想在遊戲場景中使用該名稱。這裏的第一個場景包括一個片斷怎樣訪問元素(它的工作原理):Unity:從不同場景訪問UI InputField

public InputField nameInput; 
DontDestroyOnLoad (nameInput); 

/2 ways of accessing the UI element 
GameObject.Find("NameInput").GetComponent<InputField>().text; 
nameInput; 

現在我不知道爲什麼我無法從其他場景訪問這個元素?謝謝你的幫助!

回答

3

我覺得答案很明顯。當改變場景時,前一場景的所有對象都是破壞(除非你調用一個叫做DontDestroyOnLoad的特定函數,請記住這個函數在根對象上必須被稱爲)。

您必須將名稱保存在永久位置

你在找什麼是數據持久性。統一對這個話題的教程:https://unity3d.com/fr/learn/tutorials/topics/scripting/persistence-saving-and-loading-data

這篇文章也是在我看來相當不錯:http://naplandgames.com/blog/2016/11/27/saving-data-in-unity-3d-serialization-for-beginners/

在你的情況,一個簡單的PlayerPrefs就足夠了:

// First scene : 
PlayerPrefs.SetString("Player Name", nameInput.text); 

// ... 

// Second scene : 
string playerName = PlayerPrefs.GetString("Player Name"); 
+0

你打我吧:) – Kardux

+0

謝謝,正是我一直在尋找! – Twister013