0
\$\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?

| improve this question | | | | |
\$\endgroup\$
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);
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ It worked! Thanks! \$\endgroup\$ – Petro Koval Jul 8 '19 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.