Search Unity

Question Replace GameObject with Prefab and maintain scene references

Discussion in 'Scripting' started by nehvaleem, Dec 4, 2020.

  1. nehvaleem

    nehvaleem

    Joined:
    Dec 13, 2012
    Posts:
    438
    I am wondering if it is possible to replace a GameObject (or a prefab) in the scene with another prefab, but still maintain all the references from and to other objects in the scene.

    For example: I am trying to make my life a little bit easier when it comes to gameplay setup.

    I've got:
    - base prefab "unit"
    - multiple prefab variants "character X", "character Y" and so on and those are based upon the base prefab "unit".

    The problem is that I don't have all the character prefabs ready (they are missing models) so I am using placeholders for those. Placeholders are just another prefab variants of the base "unit", but with temporary model.

    Now I want to replace those placeholders with the correct prefabs but I would like to maintain all the references and serialized calls from the placeholder. For example: I've got a PlayableDirector set up with bindings using my placeholder. I would like to swap placeholder for correct variant and not break the bindings set up on PlayableDirector.

    Things I've tried so far:
    1) Replacing prefab in the scene by dragging while holding ALT key. Prefab is being replaced but there is no Undo option for that operation and it also breaks the references for PlayableDirector.
    2) PrefabUtility.ReplacePrefab with the replace name based option but it still seems to break those references
     
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    How many components are on each prefab? You can click the elipses menu on a component and copy it, then paste it as a new component on another object, and I believe doing so retains any assignments in the Inspector.

    But if you have these prefabs already, can't you just swap the models out and leave everything else alone? Maybe I'm not understanding exactly what you have going on.
     
  3. nehvaleem

    nehvaleem

    Joined:
    Dec 13, 2012
    Posts:
    438
    Nevermind. The new PrefabUtility.SaveAsPrefabAndConnect (or something like it) does the trick for me
     
  4. snifo

    snifo

    Joined:
    Mar 6, 2015
    Posts:
    15
    Can you explain how you did this? I'm looking at the script reference but I have no idea how to do this. I have to edit a lot of scenes and if I have to do this by hand I will go crazy...

    Edit: This might be the solution https://github.com/Moolt/SmartReplace
     
    Last edited: Feb 22, 2021