Search Unity

Change base of prefab variant.

Discussion in 'Prefabs' started by koirat, Feb 25, 2019.

  1. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    Is there a way to change base of a prefab variant, or add new base to prefab without a base ?

    Or we got no other choice than completely rebuild our prefabs and all references associated with them.
     
  2. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    639
    Check this presentation for some ideas of the refactorings you can do


    Edit: Jump to 27min for the bit on refactoring.
     
    Last edited by a moderator: Oct 30, 2021
    lupa984, sprakash99 and Tommy4421 like this.
  3. runevision

    runevision

    Joined:
    Nov 28, 2007
    Posts:
    1,892
    It's not something that there exists a good clean workflow for at the moment.

    Given it's not possible to use an existing Prefab as a base, but a new one has to be created, what would be the best workflow in your opinion? To be able to specify that Cat should have a base (Animal) and Animal will initially be just a single empty GameObject? This way you could selectively apply overrides from Cat to Animal afterwards. The problem with the current approach is that there is no operation which is the "reverse" of applying overrides.

    To be clear, the various refactoring operations that are currently possible were not specifically designed (apart from some minor workflow tweaks to reduce confusion) - they are just side effects of how the Prefabs system works. So if they don't seem ideal, it's because it's not a feature we actually spent time on, but one that just appeared as a (limited) bonus by itself. Like many potential improvements, it's something we can definitely see it would be nice to improve upon if time and resources permits.
     
    detzt and hellobody like this.
  4. runevision

    runevision

    Joined:
    Nov 28, 2007
    Posts:
    1,892
    Well, it's not that simple. Not all overrides can move freely around.

    • Property override: If you apply it to the base, then it's just the new value of the base. Even if you make the property an override again in the Variant, you wouldn't get the previous original value of the base back.
    • Added components and added GameObjects: These work well for moving between base and Variant.
    • Removed component: If you apply this to the base, it will just destroy the component on the base. This is not reversible, so you can't "extract" a removed component override from a base to the Variant and cause the component to exist again on the base that way.
     
  5. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    For me it would be ok even if the content was completely deleted (or moved into some new container inside prefab "OldContent" or some other name :) ) during the change of base prefab.

    I can always repair what I have to.
     
  6. Shrubokrant

    Shrubokrant

    Joined:
    Oct 2, 2016
    Posts:
    80
    I agree. Giving us access to the possibility, even if only through PrefabUtilities and with the risk of losing data would be a great plus.
    It happens to me regularly now that I did not foresee a need in one of my prefab that has multiple variants, and now need to make it derived from another base. I would be ok with having to fix stuff around since this would still take way less time than having to delete all my prefabs and redo them all over again.

    By the way, it is quite frustrating that you cannot change the hierarchy or delete game objects in variants: you can delete components which lets you practically delete the game object by removing all the components, and passing the game object inactive and tagged EditorOnly, but it would be great to have a cleaner way to do that
     
  7. Deleted User

    Deleted User

    Guest

    I very frequently run into issues caused by these limitations, it's like Prefabs are so close to being really good, but they just miss the ball on a few things. Resorting to hacks like Bill-Sansky described is pretty disappointing, but unfortunately seems like all we can do at the moment. Hopefully this will be improved in 2020.

    Imagine if git only let you add or modify lines of code, but you could never delete a line of code (although strangely you can delete whitespace)... just comment out lines you don't want until git 2020 yolo!
     
  8. mykillk

    mykillk

    Joined:
    Feb 13, 2017
    Posts:
    60
    The way I just worked around this was to create a dummy prefab variant of the new base I want to change to. Opened it up in a text editor to get the File ID & GUIDs of the new base prefab. Then I opened up my existing prefab variants and changed the referenced IDs. This worked cleanly because the old & new base prefab had the same Component layout.

    I think Unity really should have built-in support for being able to change the base prefab. Even if that means the values in the variant get reset. Because as the others have mentioned, it is a much bigger ordeal when you have to delete and recreate alllllll your prefab variants when the base prefab needs to be changed. And you still end up with default values in the new variants anyway.
     
    Last edited: Oct 3, 2019
  9. AndrewKaninchen

    AndrewKaninchen

    Joined:
    Oct 30, 2016
    Posts:
    149
    Yeah, really think this should be a thing. I've been thinking about some ways to implement an idea I have and just hit this limitation. It's a pretty big deal for the system I was thinking about, as it would be much better to use if a designer could create a specific implementation of something and then, after that, abstract it's functionality as a parent class. It's actually something quite common in class-oriented programming as well, to be fair, so it makes sense as a viable workflow for something which is pretty much that.
     
  10. phobos2077

    phobos2077

    Joined:
    Feb 10, 2018
    Posts:
    350
    Is this being looked into? Seems like such a commonly needed feature missing.
     
    Alic likes this.
  11. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    639
  12. phobos2077

    phobos2077

    Joined:
    Feb 10, 2018
    Posts:
    350
    Thanks for answering. I also miss the ability to move game objects to/from prefab variant base and turn a normal prefab into variant by extracting all of it's contents to new base. Very common situation:

    - I have a mono behaviour view/presenter class for a UI element (to app) with a accompanying prefab. Everything is fine.
    - New UI features arrive and now I need a second prefab, but it is visually similar to the first one and also logically related.
    - In C# I create a new base class for my old MB, move common presentation functionality there. Create a second sub-class for a new element (so now I got one base class and 2 derived).
    - Naturally I want to mirror the same changes in prefabs. So I need to end up with one base prefab with common UI objects + 2 prefab variants with custom objects for each new element + appropriate monobehaviours. Also I don't want to break any instances of the original prefab (which should be now replaced with one of the two variants).

    Current workflow required:
    1. Create a copy of original prefab and remove anything from it except common objects.
    2. Create a prefab variant from this new prefab and manually copy stuff from the original prefab to end up with the same
    end result as before.
    3. Drag&drop the new prefab variant over the original prefab, to effectively replace all instances with the new variant.
    4. Delete the extra prefab variant I now ended up with.
    5. Create another prefab variant for second element.

    I think this process should be simpler, like in code where you just simply create a base class and move some code to it.
     
  13. OndrejP

    OndrejP

    Joined:
    Jul 19, 2017
    Posts:
    304
    By dragging prefab root into project, you can create new base for a prefab.

    I'd highly appreciate if you could do that, but instead create empty base for the prefab.
    This would allow me to create a base and then selectively move changes from prefab to it's base
    (using Apply Overrides on specific objects / components)
     
    ThomLaurent likes this.
  14. OndrejP

    OndrejP

    Joined:
    Jul 19, 2017
    Posts:
    304
    I have same issue with "generalization" of existing prefabs as mentioned above.

    Good workflow IMO would be:
    1) Create empty base prefab from Cat (name it Animal)
    2) Apply added game objects and components from Cat to Animal

    At least for my use case, this would be sufficient.
    I'm not aware of a solution which would allow me to create empty base prefab in Unity.

    But there's solution when manually editing YAML, so Unity team should be able to add this workflow:
    1) Create new empty Animal.prefab file, add YAML header
    2) Move root GameObject from the Cat.prefab into Animal.prefab and give it new ID
    3) Move Transform from Cat.prefab into Animal.prefab, keep it's ID
    4) Remove all m_components from this GameObject in Animal.prefab, except Transform
    5) Save Animal.prefab, give it GUID
    6) Create PrefabInstance object in Cat.prefab
    7) Assign PrefabInstance.m_sourcePrefab, use GUID of Animal.prefab from step 5
    8) Create GameObject in Cat.prefab (our new root)
    9) Assign it original ID from step 2
    10) Assign m_CorrespondingSourceObject, use new ID from step 2 and GUID from step 5
    11) Assign m_prefabInstance from step 6
    12) Save Cat.prefab

    I think something similar is already being done when creating new base prefab (open prefab, drag prefab root into project).

    I'd create a script for this, but parsing Unity version of YAML seems hard and error prone.
    I'd be much happier if Unity team did this properly.
     
    phobos2077 likes this.
  15. Discipol

    Discipol

    Joined:
    May 6, 2015
    Posts:
    83
    I am also needing this. I have 50+ buttons in various popups in my entire game. When I added sound effects for buttons, I had to go through...all of them. They where indeed variants but variants of a variety of bases.

    What I wished to do is to change their base then fix up the variants. Instead, I am threatened with 50+ missing messages and destroyed RectTransform so I can't even use that Replace Prefab utility.
     
    phobos2077 likes this.
  16. Vivraan

    Vivraan

    Joined:
    Feb 2, 2018
    Posts:
    26
    Last edited: Sep 28, 2020
    TheHeftyCoder and phobos2077 like this.
  17. mmalley

    mmalley

    Joined:
    Apr 25, 2019
    Posts:
    2
    Howdy :). Sorry for necromancy, but I have a solution to at least one of the problems discussed... though it may not be what people are really looking for.

    My problem:
    • My team had a base object which all other objects are variants of.
    • I have made lots of things out of this base object.
    • We made some new tech that changed how our camera works - and visually broke several 'types' of assets but not others.
    • To fix this issue, I needed to adjust the base object, but doing so would actually break every other object that was not one of these 'types'.

    Solution:
    • We duplicated the original base object and named it something else (v2).
    • We opened each ".prefab" of all the variants which were the visually broken 'types' in a text editor, as well as both the original base object and the v2.
    • We did a search & replace in each ".prefab" for the GUID from the original and changed them into the v2.
    • Then we were able to adjust the v2 into the hierarchy we wanted without breaking all the other assets.
    • I was able to do this with Unity running, and it updated it real time no problem.
    I hope that helps some folks :).

    Cross posting to https://forum.unity.com/threads/ability-to-reparent-or-rebase-a-prefab-variant.613429/ for visibility.
     
    rhys_vdw likes this.
  18. OndrejP

    OndrejP

    Joined:
    Jul 19, 2017
    Posts:
    304
    @mmalley Thanks for posting this, that's a good solution for a particular case!

    Do you have any approach to the problem where you would need to create new empty base prefab?
     
  19. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    I'm literally crying.
    This problem returns to me like a boomerang.
    Today I have again made attempt to add empty base prefab.

    My attempt was to create NewBasePrefab (normal prefab) that contains nothing and than edit my previous base prefab *.prefab file by adding this lines.

    Code (csharp):
    1.  
    2. --- !u!1001 &487716553614380410
    3. PrefabInstance:
    4.   m_ObjectHideFlags: 0
    5.   serializedVersion: 2
    6.   m_SourcePrefab: {fileID: 100100000, guid: 5155086ecf5dc7c439eef019808d7132, type: 3}
    7.  
    Where guid would point to the NewBasePrefab.
    This actually made BasePrefab inherit from NewBasePrefab. Unfortunately all my derived prefabs and my BasePrefab became empty.

    I'm so angry that we have to investigate all this so blindfolded since documentation is so bad or just missing. (to this day I don't know what is this fileID - it got nothing to do with files right ?)

    I'm angry that they added functionality like inserting prefab in the middle of hierarchy but you cannot control the process in any way since you will not be able to add empty one and it basically makes your current prefab empty. Just make this damn "Add Empty Base" button.

    I'm wondering if I shot myself in the foot with this technology.
    I could have tried to do stuff with prefabs aggregation instead of inheritance but who would have thought that such an obvious features are going to be missing even after months of complains from the users.


    In the end I want to scream to all the people that started designing they're hierarchy chain .
     
  20. OndrejP

    OndrejP

    Joined:
    Jul 19, 2017
    Posts:
    304
    @koirat This is big missing piece for me as well.
    You can take a look at my answer #14 which describes how to do it manually.

    It complicated, because you have to move existing GameObject and Transform into new base prefab.
    Then reference it in existing prefab.
     
    koirat and phobos2077 like this.
  21. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    I think I did this. You Mister OndrejP inspired me even though I have made it a little different way.
    And finally I think I know what is fileID - terrible terrible name. It basically is an ID of object inside current file.
    In a *.prefab file this bold thing.
    Since your way was a little to convoluted I tried something that i thought might be easier.
    The general idea was to create new base prefab by dragging current base prefab root from prefab edition hierarchy window into directory and than clicking on a "Create Base" button.
    What we got now is NewBase with everything that was in previous Base.
    From here everything must be done manually by editing files (*.prefab).

    "All" we have to do is to move all objects (except GameObject and Transform) from NewBase to Base. Repair the linking inside Base and remove all references to components that we moved from GameObject in NewBase.

    What is important to do in Base:
    Tomorrow I will try it on something different than test prefabs.
     
  22. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    Made it your way, with the difference that I have created empty prefab first so my new Base GUID was created for me automatically.

    Also I had to do this below for my transform so I had to change transform id in my new base instead of keeping old one.
    Code (csharp):
    1.  
    2. --- !u!4 &5967478523351744674 stripped
    3. Transform:
    4.   m_CorrespondingSourceObject: {fileID: 3967478523351744674, guid: b3e96b8888ba95d4c8d701bf58c4f816,    type: 3}
    5.   m_PrefabInstance: {fileID: 4877565999654225373}
    6.   m_PrefabAsset: {fileID: 0}
    7.  
    For now it is working, how long it will take for it to break ;)
    After all manual editing just begs for catastrophe.
     
    phobos2077 likes this.
  23. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    UNFORTUNATELY I DON'T HAVE GOOD NEWS AND MY NEGATIVE PREMONITIONS BECAME REALITY.

    MY PREFABS ARE QUITE BIG SO IT WAS A GOOD CRASH TEST FOR MANUAL METHOD OF ADDING EMPTY BASE PREFAB.
    SO BASICALLY EVERYTHING WENT WITHOUT ERRORS.
    I EDITED FILES WITH UNITY3d NOT LAUNCHED.
    STARTED UNITY3d - IMPORT WAS CLEAN.
    PREFABS SHOWN DURING PLAYMODE WORKED PROPERLY.

    EVERYTHING STARTED TO FALL APART WHEN I EDITED THE PREFABS. (ACTUALLY ENABLING AND DISABLING COMPONENT ON PREFAB WAS ENOUGH):

    THE REFERENCES STARTED TO DISAPPEAR - EX: LINKS TO PREFABS ON MY SCENE (MISSING).
    EVEN SOME GAMEOBJECTS DISAPPEARED FROM MY PREFABS (I KNOW THEY WERE STILL THERE SINCE THEY WERE PRESENT IN THE FILES)




    I have wasted few full work days on this.
    Blind manual editing is just to risky, it's not an option in current state of the engine.
    And please don't tell me not to scream.
     
  24. OndrejP

    OndrejP

    Joined:
    Jul 19, 2017
    Posts:
    304
    Please scream more so Unity Prefab team can hear you and add this IMPORTANT workflow.
     
  25. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    I will try like this.
    So how is it going ?
     
  26. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    639
    @koirat

    Large part of R&D switched focus to stabilizing Unity 2021.1, including the Prefabs team, so right now we grinding through all the bugs that have been reported and that is taking some time. More details here https://blogs.unity3d.com/2020/08/13/the-road-to-2021/

    Improving the refactoring of prefabs is still in the top 3 of our priorities once the bug counts is back to a manageable number.
     
    Xriuk, NotaNaN, Alic and 5 others like this.
  27. sp-LeventeLajtai

    sp-LeventeLajtai

    Joined:
    Jul 11, 2019
    Posts:
    10
    What about reordering additional components on a prefab? Right now if you try to reorder components on a prefab the Editor shouts at you to do that in the base prefab, even though those components do not exist there, so you can't do anything there. It doesn't help that in some cases the Editor randomly reorders the components...

    It seems really weird that reordering additional components is disallowed. Why? What is the reasoning there, if any? And if it is a bug or missing feature, is it being looked into?

    Thanks!

    Ps. there are no details about prefab workflow in this blog post...
     
    NotaNaN and AndrewKaninchen like this.
  28. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    639
    @sp-LeventeLajtai

    For a long time there has been a technical reason for not being allowed to reorder components. These technical reasons are soon removed, in order to fix a different problem, and then we can look into allowing reordering components. This is not a promise that it will happen soon, but it is certainly on our minds.
     
    MikeGDev, NotaNaN, orreborre and 5 others like this.
  29. robochase

    robochase

    Joined:
    Mar 1, 2014
    Posts:
    244
    I'll +1 this, it would be really helpful to be able to make a base/master prefab after the fact. It's hard to know how a project will grow over time, and before you know it, you've got a handful of things that should have been prefab variants, but they're not :/
     
    NotaNaN and phobos2077 like this.
  30. NotaNaN

    NotaNaN

    Joined:
    Dec 14, 2018
    Posts:
    325
    Did the lack of ability to change the base prefab of a prefab variant ever get addressed?
    If so, what Unity version did it land?
    If not, why has it not been made a priority to fix this?
     
  31. krav_tzar

    krav_tzar

    Joined:
    Sep 28, 2015
    Posts:
    4
    So did anyone manage to get anything working?

    I tried making an empty prefab and tried to reparent some existing prefabs to it (by editing the .prefab file), but i didnt manage to keep everything connected.
     
  32. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,074
    I don't know of any successful attempt.
    I have tried many times and something always broke.
     
  33. AdamBebko

    AdamBebko

    Joined:
    Apr 8, 2016
    Posts:
    168
    Adding a base prefab to existing prefabs is an important workflow, It would be very helpful for me as well. Hopefully this gets figured out soon.
     
    phobos2077, NotaNaN and OndrejP like this.
  34. OndrejP

    OndrejP

    Joined:
    Jul 19, 2017
    Posts:
    304
    I've created new Feature Request, hopefully Unity team will pick that up:
    https://forum.unity.com/threads/create-empty-base.1317819/

    In 2022.2, they did some work on Prefabs:
    • Prefabs: Replace Prefab Asset of Prefab intsance. With this feature you can now replace the Prefab Asset for a Prefab instance that exists in a Scene or nested inside other Prefabs. This will keep the Prefab instance position, rotation and scale in the Scene but merge the contents from the new Prefab Asset while by default maintaining as many overrides and references as possible using name based matching.
    It's not what we want, but at least it's something. I hope they will continue adding important features.
     
    sarahnorthway and NotaNaN like this.
  35. ShawnFeatherly

    ShawnFeatherly

    Joined:
    Feb 22, 2013
    Posts:
    57
    Inserting a new prefab variant into the middle of a hierarchy chain always seems to cause child prefabs to lose their overrides. Even with the Unity dialog that's supposed to handle it, mentioned in https://forum.unity.com/threads/ability-to-reparent-or-rebase-a-prefab-variant.613429/#post-5178902 . Yet, adding a new base to a prefab without a base, a prefab that is NOT a variant, maintains all overrides. To do this, open the root prefab, the one that isn't a variant of anything, then drag it from the Hierarchy window into the Project window. This will give you a dialog with only a "Create Base" and "Cancel" button.
    upload_2022-8-16_14-8-21.png
     
    koirat likes this.
  36. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    Super duper necro time. Is this still the case?

    We've just been keeping usage to a minimum and re-making stuff by hand where we have to, but it'd be really nice if this was improved.
     
    OndrejP and NotaNaN like this.
  37. Sotalo

    Sotalo

    Joined:
    May 3, 2014
    Posts:
    3
    So, I updated my sign mesh to have two materials, but the mesh in prefab for whatever reason only has one and refuses to show the other material. I spent a long time making a UI canvas for world signs and do not want to repeat that work, but the mesh is broken, no way to change to a new mesh, and no way to update it.

    ...Wow. Some things Unity does are actually really cool, but then it does things that really screw people over. Next time I'm just gonna make empty objects as the base for all my prefabs.
     
  38. krav_tzar

    krav_tzar

    Joined:
    Sep 28, 2015
    Posts:
    4
    Unity 2022.2.0 has the option to edit a current prefab and select a parent for it!

    And you can unpack a prefab and select a different parent for it!

    Finally!!!
     
    thelosev, peter_sibiro and SisusCo like this.
  39. FredTuna

    FredTuna

    Joined:
    Dec 28, 2016
    Posts:
    16
    I made a tool to select prefabs you want to make variants of another prefab using the new 2022.2. Note that this could break external references to components in the modified prefabs from other prefabs or Scriptable Objects in the project. I had to manually fix some of those by finding the file ids that changed. It was still much faster to do it this with the new 2022.2
    ConvertToPrefabInstance
    function.

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using System.IO;
    3. using System.Linq;
    4. using UnityEditor;
    5. using UnityEngine;
    6.  
    7. public class MakePrefabVariantWindow : EditorWindow
    8. {
    9.  
    10.    [MenuItem("Assets/Make Prefab Variant Of...", false, 15985)]
    11.    private static void OpenWindow()
    12.    {
    13.       selectedPrefabsFoldout = false;
    14.       selectedPrefabs        = Selection.gameObjects.Where(o => PrefabUtility.GetPrefabAssetType(o) is PrefabAssetType.Regular or PrefabAssetType.Variant).ToList();
    15.       GetWindow<MakePrefabVariantWindow>().ShowUtility();
    16.    }
    17.  
    18.    [MenuItem("Assets/Make Prefab Variant Of...", true, 15985)]
    19.    private static bool MakePrefabVariantValidate()
    20.    {
    21.       return Selection.objects.Any(o => PrefabUtility.GetPrefabAssetType(o) is PrefabAssetType.Regular or PrefabAssetType.Variant);
    22.    }
    23.  
    24.    static GameObject sourcePrefab;
    25.    static List<GameObject> selectedPrefabs = new List<GameObject>();
    26.    static bool selectedPrefabsFoldout;
    27.  
    28.    protected  void OnGUI()
    29.    {
    30.       selectedPrefabsFoldout = EditorGUILayout.Foldout(selectedPrefabsFoldout, "Selected Prefabs");
    31.       if (selectedPrefabsFoldout)
    32.       {
    33.          foreach (var selectedPrefab in selectedPrefabs)
    34.          {
    35.             EditorGUILayout.ObjectField(selectedPrefab, typeof(GameObject), false);
    36.          }
    37.       }
    38.    
    39.       sourcePrefab = EditorGUILayout.ObjectField("Source Prefab", sourcePrefab, typeof(GameObject), false) as GameObject;
    40.  
    41.       if (sourcePrefab == null || PrefabUtility.GetPrefabAssetType(sourcePrefab) is not PrefabAssetType.Regular and not PrefabAssetType.Variant)
    42.          GUI.enabled = false;
    43.    
    44.       if (GUILayout.Button("Make Selected Prefabs Variants"))
    45.       {
    46.          MakePrefabVariants();
    47.          this.Close();
    48.       }
    49.    
    50.       GUI.enabled = true;
    51.    }
    52.  
    53.    void MakePrefabVariants()
    54.    {
    55.       GameObject prefabVariant = null;
    56.       ConvertToPrefabInstanceSettings convertToPrefabInstanceSettings = new() { changeRootNameToAssetName              = false,
    57.                                                                componentsNotMatchedBecomesOverride  = true,
    58.                                                                gameObjectsNotMatchedBecomesOverride = true,
    59.                                                                logInfo                              = true,
    60.                                                                recordPropertyOverridesOfMatches     = true,
    61.                                                                objectMatchMode                      = ObjectMatchMode.ByHierarchy
    62.                                                             };
    63.  
    64.       foreach (GameObject iteratedPrefab in selectedPrefabs)
    65.       {
    66.          string     iteratedPrefabPath = AssetDatabase.GetAssetPath(iteratedPrefab);
    67.        
    68.          //Make new prefab, unpack it and make it a variant of the source prefab
    69.          GameObject newPrefabInstance  = PrefabUtility.InstantiatePrefab(iteratedPrefab) as GameObject;
    70.          PrefabUtility.UnpackPrefabInstance(newPrefabInstance, PrefabUnpackMode.OutermostRoot, InteractionMode.UserAction);
    71.          PrefabUtility.ConvertToPrefabInstance(newPrefabInstance, sourcePrefab, convertToPrefabInstanceSettings, InteractionMode.UserAction);
    72.        
    73.          //Keep old prefab as backup
    74.          string oldFileName = Path.GetFileNameWithoutExtension(iteratedPrefabPath) + "_old.prefab";
    75.          System.IO.File.Copy(Path.Combine(Path.GetDirectoryName(Application.dataPath) ?? string.Empty, iteratedPrefabPath), Path.Combine(Path.GetDirectoryName(Application.dataPath) ?? string.Empty, Path.Combine(Path.GetDirectoryName(iteratedPrefabPath), oldFileName)), true);
    76.        
    77.          //Save new prefab variant
    78.          prefabVariant = PrefabUtility.SaveAsPrefabAsset(newPrefabInstance, iteratedPrefabPath, out bool success);
    79.  
    80.          Object.DestroyImmediate(newPrefabInstance);
    81.        
    82.          if (!success)
    83.          {
    84.             Debug.LogError("Failed to make prefab variant of " + iteratedPrefabPath);
    85.             continue;
    86.          }
    87.       }
    88.    
    89.       //Select the latest made prefab variant
    90.       if (prefabVariant != null)
    91.          Selection.activeObject = prefabVariant;
    92.    }
    93. }
     
    Last edited: Dec 16, 2022
    Sarai and SisusCo like this.
  40. krav_tzar

    krav_tzar

    Joined:
    Sep 28, 2015
    Posts:
    4
    Thanks @FredTuna! I will grab it and use it when needed, if you make an update anytime, please post it here as well :)
     
    FredTuna likes this.
  41. a52

    a52

    Joined:
    Mar 15, 2018
    Posts:
    18
    This might not work for all situations, but there is a way to do this in the current version (I'm on 2022.3 -- it may work in earlier versions as well).

    1. Right click your child object in the hierarchy. **Prefab > Unpack completely**
    2. **Reconnect Prefab** to the object you want as the new parent.

    Note that this creates it as a new prefab, so you'll have to replace any usages of the previous child prefab. But with the new quick-replace prefab features, that's not too bad in certain cases.
     
  42. PandaArcade

    PandaArcade

    Joined:
    Jan 2, 2017
    Posts:
    130
    Just adding my vote for this... Unity please add this feature!