Find GameObject in next scene in same function? (C#)

Hello, I have what is probably a simple question:

If I switch scene in a function. how can I do next code:

    public void YouWin(){
    		SceneManager.LoadScene ("youWin");
            GameObject.Find ("TotalScore").GetComponent<TextMesh> ().text = "Total " + GameObject.Find ("guiScore").GetComponent<TextMesh>().text;

I did it by checking in OnLevelLoaded() weather GetActiveScene().name matches “youWin” string and then running that same line, but I would like to avoid checking every time, especially when I know it needs to be executed just once, exactly then :slight_smile:

Thanks!

PS: “guiScore” is persistent 3DText, “TotalScore” is also 3DText that exists only on “youWin” scene. This function is in a script of a persistent GameManager empty object.

A normal LoadScene always loads the scene until the next frame so directly after the call, the scene remains unloaded. (LoadSceneAsync is allowed to take even more frames - you would have to check for the Scene.IsLoaded property).

So if you are inside an object that will survive the scene loading, you can use coroutines to wait for the new scene:

public void YouWin()
{
	StartCoroutine(YouWin_Coroutine());
}
IEnumerable YouWin_Coroutine()
{
	SceneManager.LoadScene ("youWin");
	yield return null; // wait for scene to be loaded
	GameObject.Find ("TotalScore").GetComponent<TextMesh> ().text = "Total " + GameObject.Find ("guiScore").GetComponent<TextMesh>().text;
}