- Home /
Create reference to Hierarchy objects that persists between different scene loads
Hi there, I need some help solving an issue:
I have created a basic custom occlusion culling system. The system creates a list of visible objects (as in a list of mesh renderers) for every camera position in my game. At the moment It creates this list in the editor as it is rather time consuming and I don't want to do this in the game. When I run the game on a device, I would like to turn on/off the mesh renderers based on whether or not they are in the "baked" list.
The problem I have is how do I store a list of MeshRenderers that live in the hierarchy in a scriptable object or a file of some sort so that they will persist between scene loads? I tried looking into GUID but it seems that this is for assets in the asset database rather than objects in the hierarchy. I also looked into instance ID, but it seems that these ID's are not the same everytime you load the scene.
What is the correct way to get a reference to a GameObject in the hierarchy that won't change when you reload the scene?
You can't reference assets (within you project view) in your instantiated objects (in scene). You still can come up with some dynamic look up solution during runtime but it is somewhat weird. I would instantiate all objects from a list of prepared prefabs at the beginning of the game rather.
Answer by metalted · Jul 08, 2019 at 07:12 AM
You can make use of the DontDestroyOnLoad() function. If you call this function in the Start() function of your object, it won't be destroyed when the next scene is loaded. If you save the List of Renderers in this script and make the renderer gameobjects childs of this object, they will all be transferred to the next scene. This will probably be a good way to handle the situation.
Thanks for the suggestion. Although I actually want to create the list of objects in the editor and have them available in the game. So when I start the game I need to already have a list of objects ready to go
Answer by misher · Jul 08, 2019 at 07:37 AM
In your scene you have instances of assets and they are organized into hierarchy of gameobjects. An instance in a scene (basically, components attached to game objects) can naturally reference your assets (in project view) but not the other way around, there is no way an asset can reference an instance in the scene.
You can create a list of prefabs to be instantiated and make them into list (in some scriptable object for example), then, when your game starts you can instantiate them all in the scene. Or you can already have all instances in the then and then look up by name or some other attribute from your list of prefabs, note that you can't use PrefabUtility.GetPrefabParent(gameObject));
during runtime to look up for the original prefab of instatiated object, you can do this only in Editor.