- Home /
Finding gameobjects prefab
HI, new to Unity.
I am working on saving the state of a simple 2d game that has runtime created game objects. I wanted to save the bare minimum and was thinking:
Position
Angle
Prefab used
Position and Angle are easy. Where I am confused is how do I find whatever prefab was used to create the gameobject? I was hoping there would be an easy filed to get the prefab used to instantiate the object but I can't seem to find one meant for production. Of course, I need whatever reference I can save to be able to be used to load those prefabs later.
Worst case I can assign unique IDs manually by attaching a script component but since there might be hundreds of prefabs that would be a non-elegant solution that I would like to avoid.
Answer by Bunny83 · Dec 09, 2017 at 10:59 PM
The concept of prefabs do not exist at runtime. At runtime a prefab is just an ordinary gameobject with the exception that it is not part of the rendering list of the scene but only exists in memory. When you use Instantiate you just create a clone of the source object which is placed into the scene. Instantiate can clone any UnityEngine.Object. The instantiated object has no information where it came from.
Generally if you want to serialize the information of the source prefab you have to store that information inside the cloned object yourself. The best way is usually that you have your prefabs in a globally accessible array and you simply store the index of the prefab. Another way, if indices might be too messy or the number of prefabs might change you can also use the prefab name as long as it's unique, You would do the same and keep a list of all prefabs available but to access them you could create a Dictionary to do a name lookup.
Generally when you instantiate an object you may want to store the required information in the newly created clone. Something like this:
GameObject clone = Instantiate(prefabs[prefabIndex]);
clone.GetComponent<YourScript>().prefabIndex = prefabIndex;