简体   繁体   中英

Unity: Access UI InputField from different scene

I have a first scene when I ask the player for his/her name and I want to use the name in the game scene. Here's a snippet of the first scene including how I access the element (it works):

public InputField nameInput;
DontDestroyOnLoad (nameInput);

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

Now I don't know why I can't access this element from the other scene? Thanks for your help!

I think the answer is pretty obvious. When changing scene, all the objects of the previous scene are destroyed (except if you call a particular function called DontDestroyOnLoad . Keep in mind this function must be called on the root object ).

You will have to save the name in a persistent place .

What you are looking for is data persistence. Unity has a tutorial on this topic : https://unity3d.com/fr/learn/tutorials/topics/scripting/persistence-saving-and-loading-data

This article is also quite nice in my opinion : http://naplandgames.com/blog/2016/11/27/saving-data-in-unity-3d-serialization-for-beginners/

In your case, a simple PlayerPrefs will be enough :

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

// ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM