Search Unity

[Solved] Creating Prefab Variant with script

Discussion in 'Prefabs' started by deevanth, Aug 21, 2018.

  1. deevanth

    deevanth

    Joined:
    Aug 21, 2018
    Posts:
    2
    Hello,

    I've looked into the PrefabUtility class, it doesn't seem to provide any useful method to do so.

    I also tried by script to instantiate a variant prefab, modifying it and then making it a prefab again, it doesn't keep the "base prefab" attribute in the inspector (it does if you do that in the editor and choose to create a 'new original Prefab' when making a prefab from the instantiated gameobject).


    Thanks

    Edit: Solved
     
    Last edited: Aug 22, 2018
    macagu likes this.
  2. runevision

    runevision

    Unity Technologies

    Joined:
    Nov 28, 2007
    Posts:
    1,598
    The API is a bit more raw than the Editor workflows.

    To create a new Variant, use SaveAsPrefabAsset on a Prefab instance. This will have that instance as its base.
    To create a new original Prefab Variant based on an existing Variant, which uses the same base as that Variant, first use UnpackPrefabInstance on an instance of the existing Variant, then call SaveAsPrefabAsset on the unpacked instance.

    You can use those workflows in the Editor as well, the dialog boxes just provide some shortcuts which performs those multiple steps for you.
     
    Last edited: Aug 22, 2018
    macagu, Pelican_7 and mattpwibbu like this.
  3. deevanth

    deevanth

    Joined:
    Aug 21, 2018
    Posts:
    2
    Code (CSharp):
    1.  
    2. Object source = Resources.Load(prefabPath);
    3. GameObject objSource = (GameObject)PrefabUtility.InstantiatePrefab(source);
    4. GameObject obj = PrefabUtility.SaveAsPrefabAsset(objSource, variantAssetPath);
    works like a charm ! ( I was using GameObject.Instantiate((GameObject)source) instead of InstantiatePrefab ).

    I probably won't need it anymore, but.. I wasn't able to find the SaveAsPrefabInstance method in the PrefabUtility class (version : Unity 2018.2.0x-ImprovedPrefabs).

    Thanks.
     
    runevision likes this.
  4. runevision

    runevision

    Unity Technologies

    Joined:
    Nov 28, 2007
    Posts:
    1,598
    Glad it worked! And yeah, I forgot to mention that you need to instantiate with InstantiatePrefab which is the editor way of instantiating Prefabs as opposed to instantiating Prefabs at runtime. Also, the SaveAsPrefabInstance was a typo; I meant SaveAsPrefabAsset. I corrected it above.
     
  5. arene

    arene

    Joined:
    Jan 14, 2015
    Posts:
    2
    Creating a Prefab Variant this way, when creating it from a fbx file returns null in 2019.1.8f1.
    Would it be possible to have a dedicated method that always work?
     
  6. arene

    arene

    Joined:
    Jan 14, 2015
    Posts:
    2
    I've found that AssetDatabase.LoadAssetAtPath<>() fixed my issue.