PrefabUtility.GetPrefabObject doesn't work!

I am trying to use PrefabUtility.GetPrefabObject to get prefab for scene object. However, when i get object of type “Object” and trying to cast it to game object either

var prefab = PrefabUtility.GetPrefabObject(prefabRoot) as GameObject;

or

var prefab = (GameObject) PrefabUtility.GetPrefabObject(prefabRoot);

I always get null (or InvalidCastException).

Also, when inspecting returned value, it says UnityEngine.Prefab but I’ve been unable to find this type via Object Browser or IlSpy. I’d really like to get at least name of prefab so I can fetch it myself, but this Prefab object has been useless so far for me.

So far it seems that there is either a bug I didn’t get the purpose of this function. Please advise :).

Prefabs are a pure edit time feature. At runtime prefabs don’t exist. That’s why PrefabUtility.GetPrefabObject (or PrefabUtility in general) is an editor function which can’t be used at runtime. The concept of prefabs is a bit complicated since there are different types of prefabs.

At runtime there’s no way to tell which object might have been cloned from which. At runtime prefabs are just GameObjects which are loaded, but not part of the scene and therefore they don’t get any Update or other callbacks. They purely serve as clone / Instantiate source. You can use Instantiate to clone any object derived from UnityEngine.Object. There’s no way, by looking at the clone, to tell from which source an object was created. Even at edit time if you use Instantiate the “connection” to the prefab is lost. You have to use PrefabUtility.InstantiatePrefab when instantiating a prefab in an editor script to keep the connection alive. As said this is only for in-editor usage.

Again, at runtime there are no prefabs. All you get at runtime is a bunch of serialized references to those off-scene objects to be able to instantiate (clone) them into the scene.

Workaround found with help of Unity staff:

http://forum.unity3d.com/threads/prefabutility-getprefabobject-doesnt-work.282335/#post-1863415