Accessing GameObjects when changing scenes (levels)

Basically, I have Scene1 and Scene2. I call:


And code to update a Player’s name for example. I take text from the input field and do my process magic:

GameObject.Find("InputFieldName").GetComponent<InputField>().text = "NewName";

However, Unity throws a NullReference error:

NullReferenceException: Object reference not set to an instance of an object

I know my InputField is a child of Canvas, so I tried using GetComponentInChildren() too, with the same result. So I’m not sure what’s the proper course of action is. I’ve tried loading the scene asynchronoucly, and delaying a few seconds to let it load, and many other things, os I’m not sure anymore.

If you add the following code to the script in your first scene…

void Awake () {
	DontDestroyOnLoad (this);

It will prevent the GameObject that is attached to, from being destroyed once the new scene has been loaded.

Lets assume the GameObject in the first scene is named “LoginHandler”.

You will then be able to call for the information from any public variables from the “LoginHandler” GameObject which was in the first scene, since it will now be still accessible in the New Scene, because we prevented it from being destroyed (We carried it over from the first scene to the new scene)

The following code will be a part of a script in your new scene, and will call the public variable you have set, which in your case would be the user / player name.

If you put it in your void Start() method, you will be able to collect all of the nessecary information you like, and then once you have gathered that, you can Destroy the object from the first scene and still have access to all the information you pulled if you store the information in new variables before you Destroy it.

string username = GameObject.Find ("LoginHandler").GetComponent<Login> ().usernameField;

Destroy(GameObject.Find ("LoginHandler"));

I hope this helps. If not, I can try again.