Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a prefab variant in C# script?

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?

like image 947
TenOutOfTen Avatar asked Oct 21 '25 02:10

TenOutOfTen


1 Answers

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.

like image 88
Programmer Avatar answered Oct 22 '25 15:10

Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!