[Solved] How to instantiate a component from another gameObject within DontDestroyOnload?

Hi,
I have a singleton that it attached to a gameObject that hangs on runtime below the DontDestroyOnLoad.
I can instantiate it normally from any script that is in the scene with:

states = StateManager.Instance.GetComponent<StateManager>();

But one of the scripts where i want to instantiate the singleton as well, is also located in the DontDestroyOnLoad and with that one the above code doesnt seem to work.

Any idea?
thnx!

Generally in the singleton pattern, the Instance of something actually IS the component reference. You wouldn’t normally call GetComponent<> again, but I suppose it might be harmless, just extra typing.

In your case, are you perhaps looking for GetComponentInChildren() or GetComponentInParent()?

Cheers Kurt, the two gameObjects are on the root lvl of DontDestroyOnLoad
so neither really are parent/children.

If i click on the component in gameObject tes (see attacged image) it does open the stateManager which is located on the Scripts gameObject

GetComponent finds a component ON the GameObject, what you drew is a field in one of your script with a reference to the StateManager.

From your code it looks like the reference is just the variable called “States.” Why don’t you just access that directly?

Yes i was trying to fill the “public StateManager states;” with the values from the statemanager so i can access each one of the values after with “states.IsControllable” “state.GameMode” etc guess its my old way of doing things.

I changed the code to directly access “StateManager.Instance.Iscontrollable = isControllable;” and that seems to work.

thanks a lot for pointing me in the right direction!

1 Like