Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can't get prefab root asset in prefab mode

Discussion in 'Prefabs' started by taylank, Jan 25, 2019.

  1. taylank

    taylank

    Joined:
    Nov 3, 2012
    Posts:
    182
    I'm trying to have a prefab record its own path, like this:
    Code (CSharp):
    1.  
    2. var str = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(this);
    3.  
    The above code works for an instance of my prefab, but it doesn't work when I try to execute it in prefab mode of the editor. I've tried PrefabUtility.GetCorrespondingObjectFromOriginalSource(this.gameObject) and again it works for the instance but returns null when run from the actual asset in editor prefab mode. Similarly AssetDatabase.Contains(this.gameObject) returns false when used in prefab mode.

    So how on earth do I get a reference to the root asset in prefab mode?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    Probably
    PrefabStageUtility.GetCurrentPrefabStage().prefabAssetPath;


    The choice to make prefabs in the prefab stage be considered not prefabs by the prefab utility is one of those choices that makes perfect sense when in the middle of the implementation details, but makes all code actually interacting with this horrible, because everything needs two code paths depending on the current state of the editor.
     
    iggamemaker and noio like this.
  3. pojoih

    pojoih

    Joined:
    Mar 30, 2013
    Posts:
    226
    Pretty baffled to found out this one...
    I'm trying to write and editor script where you can assign GameObjects to Objectfields and this is hard work to make them assignable for Scene Objects, ProjectWindow Objects (Prefabs) as well as children of Prefabs when in Prefab Edit Mode :(