I am trying out Unity's new prefab workflow. I want to programmatically create prefab variant(s) on an prefab I've already created. I am using Unity 2018.3.0b7. How can this be done?
The PrefabUtility.SaveAsPrefabAsset
function is used to create a prefab variant. Note that you can only create prefabs and prefab variants in the Editor not in a build. To create a prefab variant, you first have to instantiate the prefab with PrefabUtility.InstantiatePrefab
then you can use the PrefabUtility.SaveAsPrefabAsset
function to create the variant.
Load your prefab from file or get reference to your original prefab:
GameObject prefabRef
= (GameObject)AssetDatabase.LoadMainAssetAtPath("Assets/Prefabs/YourPrefabName.prefab");
Instantiate the prefab the Editor way
GameObject instanceRoot = (GameObject)PrefabUtility.InstantiatePrefab(prefabRef);
Create prefab variant
GameObject pVariant = PrefabUtility.SaveAsPrefabAsset(instanceRoot, "Assets/Prefabs/PrefabOutputName.prefab");
Clean up the instantiated object
GameObject.DestroyImmediate(instanceRoot);
Note:
You need Unity 2018.3b and above to create prefab variant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With