PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

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

 July 10, 2022     c#, path, prefab, reference, unity3d     No comments   

Issue

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 ;)



Answered By - derHugo
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing