4

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?

1

1 Answer 1

5

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.