FIndObjectOfType Problem when Changing Scenes

When I change scenes using:

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

I keep the player and some other objects constant (because I want them to be transferred between scenes). In my scripts, I’ve got FindObjectOfType() etc. in the Start() function, however this doesn’t seem to be fast enough sometimes, as I end up with references to old gameObjects (e.g. that are replaced by the new gameObjects coming from the other scene). I might have a dummy player in the scene so I can test it, but in the actual game, that player will get replaced by the “real” player when they change scenes.

My current workaround is to have a bool flag, then in the Update() loop after a timer of 0.01s, I do the FindObjectOfType stuff there, then turn the flag on. This means the references are all correct, but doesn’t seem like a good way of handling this problem.

Some pseudocode:

private Player myPlayer;
private bool foundPlayer;
private float waitTime;

Start(){
    myPlayer = FindObjectOfType<Player>(); // Sometimes not fast enough...
    waitTime = 0.01f;
}

Update(){
    if (waitTime > 0){
        waitTime -= Time.deltaTime; // Count down for 0.01s
    }
    if (!foundPlayer && waitTime <= 0){ // After 0.01s, if we don't have the reference
        myPlayer = FindObjectOfType<Player>(); // Set the correct reference
        foundPlayer = true;
    }
}

Is there a better solution to this?

If you want to do a call when a new scene was loaded, why not use:

void OnLevelWasLoaded()
{
//Blah Blah this only works when using SceneManager.Load
}

//OR

void OnLevelWasLoaded(int sceneindex)
{
//Blah Blah this only works when using SceneManager.Load
}

As far as the old gameobjects, i’m assuming you’re using a list. You could remove the “bad” gameobjects with something along the lines of:

MyHashSet.RemoveWhere(s => s == null);

This is helpful if a gameObject was once there…but has been unloaded (aka, switched scenes), therefore, it’d be null.