Hey, I searched but can’t seem to find the answer to this question - how can I open a prefab stage via script for a particular prefab? I have quite a few Edit Prefab buttons in my workflow that currently load a prefab into the scene that I’d like to change to open the prefab stage instead
I think you’re looking for this: Unity - Scripting API: PrefabUtility.LoadPrefabContents
If you want exactly the behaviour you get when opening the prefab, you can call AssetDatabase.OpenAsset.
Awesome, AssetDatabase.OpenAsset works!
I suggest caution with any modifications of prefabs using API :
I would also add, as of 2019.3, opening a prefab using AssetDatabase.OpenAsset triggers the Unity Editor to open the prefab on the PrefabStage but there’s no way to programatically talk to the PrefabStage. The Object returned by AssetDatabase.OpenAsset is NOT the object instance shown in the Unity Editor. If you edit that Object you will be editing some random Object not the the one Unity Editor is using.
AssetDatabase.OpenAsset returns a bool, so not sure what returned object you are referring to here.
What you can do is:
AssetDatabase.OpenAsset(yourPrefab);
followed by a call to:
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
But what should I do if I want to open asset with some context scene? Same case as if I open prefab mode through arrow in Hierarchy. I see context scene in prefab mode. How could I set this when I do AssetDatabase.OpenAsset()?
Or how could I simulate opening from Hierarchy via code if I have some scene and prefab in it.
OpenAsset() opens it isolated anyway
There is a non-obvious workaround for opening in context which will work back to 2020.1 where Prefab Mode In Context was introduced:
AssetDatabase.OpenAsset
has an optional int line
parameter, if you pass the instanceID of the Prefab instance object then we will open Prefab Mode In Context of that instance.
In the 2021.2 we have added PrefabStageUtility.OpenPrefab
How about closing ? how do I close a opened prefabstage scene from script
Hi bugcamper, please try out the following methods on StageUtility:
Just in case anyone ends up here like I did:
PrefabStageUtility.OpenPrefab();
works like a charm,
however, I don’t think there’s currently a way to programmatically Save & Close the Prefab Stage…