Bodo Baumstamm
Bodo Baumstamm

Reputation: 1

How to find a GameObjects Prefab during runtime with Unity version 2018.3

After updating to Unity 2018.3.0f2 I`m unable to find a GameObjects prefab while the game is running. In the previous versions i was simply using this line:

GameObject prefabObject = 
    PrefabUtility.GetCorrespondingObjectFromSource(gameObject);

But after the update this function only returns null, so I tried the new functions:

  1. PrefabUtility.GetPrefabInstanceHandle
  2. PrefabUtility.GetNearestPrefabInstanceRoot
  3. PrefabUtility.GetOutermostPrefabInstanceRoot

but all of them return null but I`m sure that I am handing a prefab over as parameter. Any ideas what I am doing wrong here?

Upvotes: 0

Views: 5077

Answers (1)

Wappenull
Wappenull

Reputation: 1379

As soon as editor start playing (Application.isPlaying=true) prefab linkage with scene game objects will be broken (blue game objects turned into gray) and thus you cannot obtain prefab related information from it.

If you really need a scenario were you want to access such information on runtime, you should save it as Serialized variable in script component so that it will later available on runtime.

For example: this is a simplified contraption of what Mirror (Unity network plugin) is doing by issuing asset ID related stuff to help distinguish each prefab to spawn things in network on runtime.

    [SerializeField] string m_AssetId;

    void OnValidate() // Which will be called on build or editor play
    {
    #if UNITY_EDITOR
         // Deposit UnityEditor API dependent into some field
         m_AssetId = UnityEditor.AssetDatabase.GetAssetPath( gameObject );
    #endif
    }

Anyway, for running editor script, if you want to test or look for original prefab. UnityEditor.PrefabUtility is somewhat hard to find a full example of how to use them.

You can refer to my git repository on how to use them with examples.

https://github.com/wappenull/UnityPrefabTester

enter image description here

Upvotes: 2

Related Questions