Search code examples
c#unity-game-enginepathreferenceprefab

How can I get a reference of a prefab asset from the code in it self?


So let's say I have this prefab asset, "P" and have this code attached to it.

public GameObject selfReference;

[ContextMenu("GetReference")]
public void GetReference()
{
    selfReference = gameObject;
}

Note that: the 'reference finding' process is trigger by ContextMenu so it is done in Edit Mode, not Play Mode; and all of this is happening in the prefab asset "P" itself, not some random instance of it placed in the scene.


So I tried

selfReference = PrefabUtility.GetNearestPrefabInstanceRoot(gameObject);

but it didn't work so tried to load it via path:

string _path = AssetDatabase.GetAssetPath(gameObject);

but it returns only blank string.

Any help plz?


Solution

  • I can only assume - since it works for me ;)

    enter image description here

    that your question is rather related to this change not being saved correctly and not being handled for undo/redo.

    You should probably do e.g.

    public GameObject selfReference;
    
    [ContextMenu(nameof(GetReference))]
    public void GetReference()
    {
    #if UNITY_EDITOR
        if(!Application.isPlaying)
        {
            UnityEditor.Undo.RecordObject(this, "fetched self-reference");
    
            if (UnityEditor.PrefabUtility.IsPartOfAnyPrefab(this))
            {
                UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
            }
        }
    #endif
    
        selfReference = gameObject;
    }
    

    besides that of course it appears a bit redundant to me to have a field for something that is exposed via the property anyway ;)