1
\$\begingroup\$

I want to get a prefab asset (that resides in Project Window) and assign it to a field like the one you get when you manually drag the prefab asset from Project Window to GameObject field:

enter image description here

But when I try to do the same thing in code (and in Edit Mode) with this function:

GameObject prefab_instance = PrefabUtility.GetNearestPrefabInstanceRoot(gameobj) as GameObject;

I get a prefab instance but not a prefab asset:

enter image description here enter image description here

How do I get a reference to prefab asset from the gameobject that was created from it?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

If I understand what you want to do, then I think you want to use PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot in combination with AssetDatabase.LoadAssetAtPath.

Like so:

string path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameobj);
GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
Debug.Log(go.name, go);
\$\endgroup\$
0
0
\$\begingroup\$

If you want to find prefab variant of an instance you should use

PrefabUtility.GetCorrespondingObjectFromSource(YourPrefabInstance)

If you want to find orginal prefab of an instance you should use

PrefabUtility.GetCorrespondingObjectFromOriginalSource(YourPrefabInstance)

It will work only in Editor mode.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .