Is there a way to identify if an object was created at runtime?

Like the title says…

For a tool I am currently building to increase my workflow I am wondering whether there is a way to identify if a GameObject was created at runtime via a script. So this has nothing to do with prefabs or not, I just want to know if the GameObject persists within the scene on disk. I know of EditorUtility.IsPersistent, but this relates to if the object is an asset that is saved on disk, i.e. it returns false for GameObjects within a scene no matter if they persist or are created dynamically.

I guess worst case would be to have a hook to fully traverse the scene when play mode is entered and save all encountered object ids, but that seems to be rather intensive…

Hi!

I don’t believe there is an option for this, however I think the following might work:

Create your own instantiation method that runs the normal instantiation code, but if in editor stores that game object in a list. (likely in a editor/editor window class)

public static Object Instantiate(Object object)
{
    Object go = Instantiate(object);
#if UNITY_EDITOR
    editorCollection.Add(go);
#endif
}

(Untested)

This may not work for you depending on your setup, but hopefully this suggestion is okay!

Yeah, I thought of that as well, however since the tool was meant to be easily added to projects - without having to require things like this - that won’t work unfortunately. I found a hacky way by using the “local identifier in file” private field via reflection (that is 0 if created during runtime - or if not yet saved), but I might just go via traversing all gameObjects when switching from editor to play mode…

1 Like