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

Saving prefabs for 2018.3 for editor script

Discussion in 'Scripting' started by lowbl_dan, Jan 30, 2019.

  1. lowbl_dan

    lowbl_dan

    Joined:
    Jan 22, 2019
    Posts:
    34
    Hi, I'm trying to save my prefab with an editor script but I keep getting an empty string when I query the path with AssetDatabase.GetAssetPath() . My editor script has buttons that destroys / creates objects within a prefab, and exiting "Open Prefab Asset Mode" does not automatically detect that change unless I change a random value in an existing component , so I figured applying the change to prefab through code might be the way to resolve this.

    The button is pressed in "Open Prefab Asset Mode".

    Code (csharp):
    1.  
    2. GameObject parentObject = PrefabUtility.GetOutermostPrefabInstanceRoot(prefabObject);
    3. string pathToPrefab = AssetDatabase.GetAssetPath(parentObject); //this returns an empty string
    4.                    
    5. bool success = false;
    6. PrefabUtility.SaveAsPrefabAsset(parentObject, pathToPrefab, out success);
    7. PrefabUtility.UnloadPrefabContents(parentObject);
    8.  
    I need some help as I'm not very familiar with the newer methods of saving prefabs.
    Thanks for viewing.
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    I'd ask in the prefabs forum rather than here.
     
  3. lowbl_dan

    lowbl_dan

    Joined:
    Jan 22, 2019
    Posts:
    34
    Sorry, i wasn't too sure which category this implementation should fall into. I will put it in prefab forums the next time.

    Anyway I managed to resolve my problem. Apparently, AssetDatabase.GetAssetPath will not work in prefab isolation mode, but since I can only destroy my child gameObjects of a prefab in isolation mode, so I had to do the following:

    Code (csharp):
    1.  
    2. string path = PrefabStageUtility.GetCurrentPrefabStage().prefabAssetPath; // this will produce a valid path in isolation mode (the arrow tab beside the name of prefab in inspector)
    3. GameObject prefabRoot = PrefabUtility.LoadPrefabContents(path);
    4.  
    5. //work directly on prefab root here, destroy child etc
    6.  
    7. PrefabUtility.SaveAsPrefabAsset(prefabRoot, path);
    8. PrefabUtility.UnloadPrefabContents(prefabRoot);
    9.  
    10.  
    the changes will be immediately reflected on the object in isolation mode, and upon exiting , changes will be saved.