[Unity 5] AddComponent Not Working After Scene Restart

I have some code that dynamically adds a component to all objects in a specific layer, which is run at Start and runs fine… until I “restart” the scene using;

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

Rerunning the following code after that still finds the appropriate GameObjects, but never adds the component to them.

void SetWater()
    {
        GameObject[] waterObjects;
        waterObjects = FindInActiveObjectsByLayer(LayerMask.NameToLayer("Water"));

        foreach (GameObject g in waterObjects)
        {
            g.AddComponent<ArcaneWater>();
        }
    }

Debugging g shows what it should, even after the restart, but for some reason it never adds the component.

I was wondering if this was a known issue or whether I’m doing something wrong.

Anyone know what’s going on?

Are you calling the above “find” code in the same frame? Scenes don’t load until the next frame after you call LoadScene. You need to stick around one frame to let the scene load, then go digging for stuff.

The find code (line 4 above) works just fine, it finds the gameobjects when you debug g in the foreach.
It just doesn’t add the component.

I ask you again,

Because sure it finds them… it’s finding the OLD ones that are about to be destroyed when you load the next scene!

Put it in a WaitForSeconds loop… it was indeed finding the old ones.

1 Like