Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Replace game object with prefab?

Discussion in 'Editor & General Support' started by DaveA, Jun 4, 2009.

  1. DaveA

    DaveA

    Joined:
    Apr 15, 2009
    Posts:
    310
    I know I can replace a prefab with a game object, but can I do the reverse? Meaning, I want to keep the same settings, at LEAST the transform, of the GO, but replace it with a prefab.

    Would make importing game objects to other scenes a little more do-able.

    Gotta be a way to script that.
     
  2. Lucas Meijer_old

    Lucas Meijer_old

    Joined:
    Apr 5, 2008
    Posts:
    436
    If I'm not mistaken, this is actually default behaviour. A prefab instance always has its transform settings as "overriden". So you can move the instance around, then change the prefab, and the instance will take on all settings from the prefab, except its transform settings.

    Bye, Lucas
     
  3. DaveA

    DaveA

    Joined:
    Apr 15, 2009
    Posts:
    310
    I should have been more clear.

    I don't want to change settings on the prefab. I want to REPLACE the ENTIRE prefab with another.

    Example:
    I make a nice particle effect. I place this in the scene in several places. Then, my partner makes a better effect on his computer. I want to replace my particles with his, so I copy his prefab to my project.

    But now, there is no way for me (that I know of!) to replace my prefab with his.
     
  4. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    Just drag an instance of his prefab from the scene hierarchy to the project pane, overriding your existing prefab.
     
  5. DaveA

    DaveA

    Joined:
    Apr 15, 2009
    Posts:
    310
    Thanks.

    Now the hard part: say you have a game object that contains one or more objects that you want to replace with prefabs. Think of them as place-holder objects. Now I want to replace the place-holders with prefabs, but without having to copy/paste all the params around. Is there a way to do that?
     
    leonelvg likes this.
  6. sunset

    sunset

    Joined:
    Nov 7, 2010
    Posts:
    61
    Hey,
    i had the same problem and wrote a little script to fix it.
    Its realy not that hard as I thougt ^^

    What it does:
    The script lets you replace a hole bunch of placeholders at the same by an predefined Prefab.
    The object you put in for replacing needs to be a Prefab.

    If you want to replace many placeholders at the same time, attach them as children to another Object. For example an
    Empty. Then declare this Parent as the object to replace.
    The script will automaticly check for its children an replace them.

    Feel free to do some improvements on the script. But please be fair enough to share it.
    So others could benefit of it.
     
  7. Ravael

    Ravael

    Joined:
    Jan 6, 2011
    Posts:
    1
    INSTANCE REPLACEMENT:

    Drag your new Prefab onto the existing GameObject in the Hierarchy while holding [Alt].
     
    Last edited: Jan 6, 2011
    Panner_, Boaz_A, Lion_C and 37 others like this.
  8. KristianHJ

    KristianHJ

    Joined:
    May 28, 2010
    Posts:
    350
    Hi

    I changed the script to allow for changing any number of gameobjects with a specific prefab.
    It also keeps the originals parents transform

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4. // CopyComponents - by Michael L. Croswell for Colorado Game Coders, LLC
    5. // March 2010
    6.  
    7. public class ReplaceGameObjects : ScriptableWizard
    8. {
    9.     public bool copyValues = true;
    10.     public GameObject NewType;
    11.     public GameObject[] OldObjects;
    12.  
    13.     [MenuItem("Custom/Replace GameObjects")]
    14.  
    15.  
    16.     static void CreateWizard()
    17.     {
    18.         ScriptableWizard.DisplayWizard("Replace GameObjects", typeof(ReplaceGameObjects), "Replace");
    19.     }
    20.  
    21.     void OnWizardCreate()
    22.     {
    23.         //Transform[] Replaces;
    24.         //Replaces = Replace.GetComponentsInChildren<Transform>();
    25.  
    26.         foreach (GameObject go in OldObjects)
    27.         {
    28.             GameObject newObject;
    29.             newObject = (GameObject)EditorUtility.InstantiatePrefab(NewType);
    30.             newObject.transform.position = go.transform.position;
    31.             newObject.transform.rotation = go.transform.rotation;
    32.             newObject.transform.parent = go.transform.parent;
    33.  
    34.             DestroyImmediate(go);
    35.  
    36.         }
    37.  
    38.     }
    39. }
     
    Last edited: Feb 15, 2022
    quibit, Bakanovskiy95, Zaddo and 10 others like this.
  9. Metron

    Metron

    Joined:
    Aug 24, 2009
    Posts:
    1,137
    Great script... thanks...
     
  10. Eyeofgod

    Eyeofgod

    Joined:
    Jun 25, 2010
    Posts:
    126
    Many thanks. It has safe me a lot of work hours
     
  11. PolyMad

    PolyMad

    Joined:
    Mar 19, 2009
    Posts:
    2,350
    Thank you Kudos, this should be a standard Unity function imho...
     
  12. morphus1

    morphus1

    Joined:
    Apr 9, 2012
    Posts:
    2
    Heya guys,
    I'm having a hard time trying to get this to work in my situation. The alt drag doesn't work for either. It says that this is not implemented yet. As for the script it says it can't find the prefab in the prefab library. any ideas?
     
  13. StubbornMinion

    StubbornMinion

    Joined:
    Apr 13, 2012
    Posts:
    4
    Hey, I just registered on the community to say thank you to sunset and kudosforludos for this script. It totally worked and saved me a lot of bother :)
     
  14. DanTreble

    DanTreble

    Joined:
    Aug 31, 2010
    Posts:
    590
    Excellent script. I modified it slightly so it copies scale and it prefills the selection

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4.  
    5. // CopyComponents - by Michael L. Croswell for Colorado Game Coders, LLC
    6. // March 2010
    7.  
    8. //Modified by Kristian Helle Jespersen
    9. //June 2011
    10.  
    11. public class ReplaceGameObjects : ScriptableWizard
    12. {
    13.     public bool copyValues = true;
    14.     public GameObject NewType;
    15.     public GameObject[] OldObjects;
    16.  
    17.     [MenuItem("Custom/Replace GameObjects")]
    18.     static void CreateWizard()
    19.     {
    20.         var replaceGameObjects = ScriptableWizard.DisplayWizard <ReplaceGameObjects>("Replace GameObjects", "Replace");
    21.         replaceGameObjects.OldObjects = Selection.gameObjects;
    22.     }
    23.  
    24.     void OnWizardCreate()
    25.     {
    26.         //Transform[] Replaces;
    27.         //Replaces = Replace.GetComponentsInChildren<Transform>();
    28.  
    29.         foreach (GameObject go in OldObjects)
    30.         {
    31.             GameObject newObject;
    32.             newObject = (GameObject)EditorUtility.InstantiatePrefab(NewType);
    33.             newObject.transform.parent = go.transform.parent;
    34.             newObject.transform.localPosition = go.transform.localPosition;
    35.             newObject.transform.localRotation = go.transform.localRotation;
    36.             newObject.transform.localScale = go.transform.localScale;
    37.  
    38.             DestroyImmediate(go);
    39.         }
    40.     }
    41.  
    42. }
     
    Bakanovskiy95 and mfatihbarut like this.
  15. Morgan

    Morgan

    Joined:
    May 21, 2006
    Posts:
    1,223
    Same Here (3.5.2) - Alt-dragging a prefab from Project into a different prefab in Hierachy does not swap in the new prefab. It does nothing. (And occasionally crashes.) I don’t need the script and didn’t try it, but dragging manually would be great!
     
  16. Ecocide

    Ecocide

    Joined:
    Aug 4, 2011
    Posts:
    293
    I know this is an old thread but thanks ALOT, because this is saving me a lot of work (and nerves).
     
  17. ojgang

    ojgang

    Joined:
    Oct 22, 2012
    Posts:
    3
    im totally noob in this....
    how to apply this script on my prefab ?
     
  18. kimberleyhansen

    kimberleyhansen

    Joined:
    Oct 10, 2011
    Posts:
    1
    Yeah, sorry guys, I also don't know how to make this work. I've created a new script (CopyComponents.cs), and the Custom > ReplaceGameObjects menu shows up...but when I try to use the option, I get a "NullReferenceException: Object reference not set to an instance of an object" error. What am I doing wrong?
     
  19. Archimagus

    Archimagus

    Joined:
    Sep 29, 2012
    Posts:
    21
    To the people that can't seem to get this to work. Make sure you scrips file name matches the class name.
     
  20. dval

    dval

    Joined:
    Jul 25, 2012
    Posts:
    24
    Thank you !
     
  21. DESTRUKTORR

    DESTRUKTORR

    Joined:
    Jul 4, 2012
    Posts:
    22
    All these seem so overcomplicated. Here, I've taken and optimized it all to work based on what game objects you have selected, rather than having to individually drag an drop every object into an array object in the window... Enjoy.

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4.  
    5. public class ReplaceGameObjects : ScriptableWizard
    6. {
    7.     public GameObject useGameObject;
    8.    
    9.     [MenuItem ("Custom/Replace GameObjects")]  
    10.     static void CreateWizard ()
    11.     {
    12.         ScriptableWizard.DisplayWizard("Replace GameObjects", typeof(ReplaceGameObjects), "Replace");
    13.     }
    14.    
    15.     void OnWizardCreate ()
    16.     {
    17.         foreach (Transform t in Selection.transforms)
    18.         {
    19.             GameObject newObject = (GameObject)EditorUtility.InstantiatePrefab(useGameObject);
    20.             Transform newT = newObject.transform;
    21.             newT.position = t.position;
    22.             newT.rotation = t.rotation;
    23.             newT.localScale = t.localScale;
    24.         }
    25.         foreach (GameObject go in Selection.gameObjects)
    26.         {
    27.             DestroyImmediate(go);
    28.         }
    29.     }
    30. }
     
    Last edited: Feb 10, 2013
    Bakanovskiy95 and susted like this.
  22. raghaaav

    raghaaav

    Joined:
    Feb 13, 2013
    Posts:
    1
    Modified so that parent-child relationships are kept intact.

    :)

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4.  
    5. /*
    6.  * http://forum.unity3d.com/threads/24311-Replace-game-object-with-prefab/page2
    7.  * */
    8.  
    9. public class ReplaceGameObjects : ScriptableWizard
    10.  
    11. {
    12.     public GameObject useGameObject;
    13.  
    14.     [MenuItem ("Custom/Replace GameObjects")]  
    15.  
    16.     static void CreateWizard ()
    17.     {
    18.         ScriptableWizard.DisplayWizard("Replace GameObjects", typeof(ReplaceGameObjects), "Replace");
    19.     }
    20.  
    21.     void OnWizardCreate ()
    22.     {
    23.         foreach (Transform t in Selection.transforms)
    24.         {
    25.             GameObject newObject = PrefabUtility.InstantiatePrefab(useGameObject) as GameObject;
    26.             Transform newT = newObject.transform;
    27.  
    28.             newT.position = t.position;
    29.             newT.rotation = t.rotation;
    30.             newT.localScale = t.localScale;
    31.             newT.parent = t.parent;
    32.  
    33.         }
    34.  
    35.         foreach (GameObject go in Selection.gameObjects)
    36.         {
    37.             DestroyImmediate(go);
    38.         }
    39.     }
    40. }
     
    Bakanovskiy95 and mfatihbarut like this.
  23. Deepestblue

    Deepestblue

    Joined:
    May 11, 2009
    Posts:
    48
    Thanks for this! I kiss the ground on which you walk. :)
     
    MarshallVisions likes this.
  24. BGitlin

    BGitlin

    Joined:
    Apr 29, 2013
    Posts:
    1
    Awesome update to the script, works great, thanks man
     
  25. dhun

    dhun

    Joined:
    Feb 25, 2013
    Posts:
    1
    Just wanted to say thanks for this, saved me a bunch of time.
     
  26. MettleRobot

    MettleRobot

    Joined:
    Nov 5, 2013
    Posts:
    3
    This is a really useful script. Thanks to everyone who worked on it :)

    There's something I've been looking to to be able to do in Unity for years now. And this script comes the closest so far...

    How hard would it be to automate this process a little more, so it could replace multiple DIFFERENT objects with DIFFERENT prefabs.

    eg. I export an FBX from Max that contains hundreds of modular instanced objects (wall sections, foliage, etc). Import it into Unity and put it in the scene where you can see it still has all the individual objects as children under a game object. And I've already made all the prefab wall sections, foliage objects, etc.

    Could I then run a script that looks at each child object, figures out which of my prefabs it matches. And then go through and replace them all. I could build whole levels in Max this way. It would be amazing!

    The instances from Max have a unique number suffix, but other than that the name of each one could be used to find it's replacement prefab.

    Even better would be if I could put this script on an empty game object in the scene and use it like a manager so it can be told which fbx (or selection of fbx's) from the Assets folder to source and then when you click go it basically runs through the process automatically leaving you with a whole lot of placed prefabs. It could maybe have an option to auto-update if it detects the fbx has been changed.

    I would pay big money for this functionality if I saw it on the Asset Store.
     
  27. Mutain

    Mutain

    Joined:
    Jun 1, 2013
    Posts:
    3
    Just added some undo support into your script.

    Code (csharp):
    1. using UnityEditor;
    2. using UnityEngine;
    3.  
    4. /*
    5.  * [url]http://forum.unity3d.com/threads/24311-Replace-game-object-with-prefab/page2[/url]
    6.  * */
    7.  
    8. public class ReplaceGameObjects : ScriptableWizard
    9. {
    10.  
    11.     public GameObject useGameObject;
    12.  
    13.     [MenuItem("Custom/Replace GameObjects")]
    14.  
    15.     static void CreateWizard()
    16.     {
    17.         ScriptableWizard.DisplayWizard("Replace GameObjects", typeof(ReplaceGameObjects), "Replace");
    18.     }
    19.  
    20.     void OnWizardCreate()
    21.     {
    22.         foreach (Transform t in Selection.transforms)
    23.         {
    24.             GameObject newObject = PrefabUtility.InstantiatePrefab(useGameObject) as GameObject;
    25.             Undo.RegisterCreatedObjectUndo(newObject, "created prefab");
    26.             Transform newT = newObject.transform;
    27.  
    28.             newT.position = t.position;
    29.             newT.rotation = t.rotation;
    30.             newT.localScale = t.localScale;
    31.             newT.parent = t.parent;
    32.         }
    33.  
    34.         foreach (GameObject go in Selection.gameObjects)
    35.         {
    36.             Undo.DestroyObjectImmediate(go);
    37.         }
    38.     }
    39. }
     
    Bakanovskiy95, SkrenZz and lmaxsmith like this.
  28. a_deadman

    a_deadman

    Joined:
    Jan 20, 2014
    Posts:
    5
    I added :

    newObject.name = go.name;

    as well as I needed the names to re-attach them to parameters in one of my scripts needed to know what was what.

    If anyone knows of a way to add the references to the new prefab's please let us know.
     
  29. AlgorithMan

    AlgorithMan

    Joined:
    Feb 13, 2014
    Posts:
    1
    Thank you so much guys! This script is a life saver!
    Here, I also added a second class which replaces objects based on their name instead of based on selection. (I have thousands of instances of the same prefab, all with broken prefab-connection - but they all have the same name, so in a situation like this, this script is more handy)

    Code (csharp):
    1.  
    2. public class BatchReplaceByName : ScriptableWizard
    3. {
    4.     public GameObject NewType;
    5.     public string Name = "";
    6.     public bool MatchCase = false;
    7.    
    8.     [MenuItem("Custom/Batch Replace By Name")]
    9.    
    10.     static void CreateWizard()
    11.     {
    12.         var replaceGameObjects = ScriptableWizard.DisplayWizard <BatchReplaceByName>("Replace GameObjects", "Replace");
    13.     }
    14.    
    15.     void OnWizardCreate()
    16.     {
    17.         GameObject[] allObjects = GameObject.FindObjectsOfType<GameObject>();
    18.         if (!MatchCase)
    19.             Name = Name.ToUpper ();
    20.  
    21.         foreach(GameObject go in allObjects)
    22.         {
    23.             if((MatchCase ? go.name : go.name.ToUpper()) != Name)
    24.                 continue;
    25.  
    26.             GameObject newObject = (GameObject)PrefabUtility.InstantiatePrefab(NewType);
    27.             newObject.transform.parent = go.transform.parent;
    28.             newObject.transform.localPosition = go.transform.localPosition;
    29.             newObject.transform.localRotation = go.transform.localRotation;
    30.             newObject.transform.localScale = go.transform.localScale;
    31.             newObject.name  = go.name;
    32.             UnityEngine.Object.DestroyImmediate(go);
    33.         }
    34.     }
    35. }
    36.  
     
    Last edited: Mar 8, 2014
    Bakanovskiy95 and Rodolfo-Rubens like this.
  30. MrPhil

    MrPhil

    Joined:
    Sep 22, 2010
    Posts:
    40
    Don't forget to put the script in a folder called Editor (doesn't matter where, just has to be called "Editor")
     
    lmaxsmith likes this.
  31. mrBeam

    mrBeam

    Joined:
    Mar 17, 2014
    Posts:
    11
    Hi, I tweaked it in to an Editor Window and now it can handle Scene objects, Prefabs and Objects!
    Enjoy and thanks!

    Code (csharp):
    1.  
    2. using UnityEditor;
    3. using UnityEngine;
    4.  
    5. public class ReplaceSel : EditorWindow
    6. {
    7.     GameObject myObject;
    8.    
    9.     [MenuItem ("Tools/ReplaceSelected %g")]
    10.     public static void ReplaceObjects() {
    11.         EditorWindow.GetWindow(typeof(ReplaceSel));
    12.     }
    13.        
    14.     void OnGUI () {
    15.         GUILayout.Label ("Use Object", EditorStyles.boldLabel);
    16.         myObject = EditorGUILayout.ObjectField(myObject, typeof(GameObject), true) as GameObject;
    17.         if (GUILayout.Button ("Replace Selected")) {
    18.            
    19.             if (myObject != null) {
    20.                 foreach (Transform t in Selection.transforms) {
    21.                     GameObject o = null;
    22.                     o = PrefabUtility.GetPrefabParent(myObject) as GameObject;
    23.                    
    24.                     if (PrefabUtility.GetPrefabType(myObject).ToString() == "PrefabInstance") {
    25.                         o = (GameObject)PrefabUtility.InstantiatePrefab(o);
    26.                         PrefabUtility.SetPropertyModifications(o, PrefabUtility.GetPropertyModifications(myObject));
    27.                     }
    28.                    
    29.                     else if (PrefabUtility.GetPrefabType(myObject).ToString() == "Prefab") {
    30.                         o = (GameObject)PrefabUtility.InstantiatePrefab(myObject);
    31.                     }
    32.                    
    33.                     else {
    34.                         o = Instantiate(myObject) as GameObject;
    35.                     }
    36.                    
    37.                     Undo.RegisterCreatedObjectUndo(o, "created prefab");
    38.                     Transform newT = o.transform;
    39.                     newT.position = t.position;
    40.                     newT.rotation = t.rotation;
    41.                     newT.localScale = t.localScale;
    42.                     newT.parent = t.parent;
    43.                    
    44.                     foreach (GameObject go in Selection.gameObjects) {
    45.                         Undo.DestroyObjectImmediate(go);
    46.                     }
    47.                 }
    48.             }
    49.         }
    50.     }
    51. }
    52.  
     
    Last edited: Mar 19, 2014
    Bakanovskiy95 likes this.
  32. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,369
    Nice script, but it has a bug which makes it unusable. This code should be place outside of the foreach:
    Code (csharp):
    1.  
    2. foreach (GameObject go in Selection.gameObjects) {
    3.  
    4.     Undo.DestroyObjectImmediate(go);
    5. }
    6.  
    So it becomes this:
    Code (csharp):
    1.  
    2. using UnityEditor;
    3. using UnityEngine;
    4.  
    5. public class ReplaceSel : EditorWindow
    6. {
    7.     GameObject myObject;
    8.     [MenuItem ("Tools/ReplaceSelected %g")]
    9.  
    10.     public static void ReplaceObjects() {
    11.  
    12.         EditorWindow.GetWindow(typeof(ReplaceSel));
    13.     }        
    14.  
    15.     void OnGUI () {
    16.  
    17.         GUILayout.Label ("Use Object", EditorStyles.boldLabel);
    18.  
    19.         myObject = EditorGUILayout.ObjectField(myObject, typeof(GameObject), true) as GameObject;
    20.  
    21.         if (GUILayout.Button ("Replace Selected")) {            
    22.  
    23.             if (myObject != null) {
    24.  
    25.                 foreach (Transform t in Selection.transforms) {
    26.  
    27.                     GameObject o = null;
    28.                     o = PrefabUtility.GetPrefabParent(myObject) as GameObject;                    
    29.  
    30.                     if (PrefabUtility.GetPrefabType(myObject).ToString() == "PrefabInstance") {
    31.  
    32.                         o = (GameObject)PrefabUtility.InstantiatePrefab(o);
    33.                         PrefabUtility.SetPropertyModifications(o, PrefabUtility.GetPropertyModifications(myObject));
    34.                     }                    
    35.  
    36.                     else if (PrefabUtility.GetPrefabType(myObject).ToString() == "Prefab") {
    37.  
    38.                         o = (GameObject)PrefabUtility.InstantiatePrefab(myObject);
    39.                     }                    
    40.  
    41.                     else {
    42.  
    43.                         o = Instantiate(myObject) as GameObject;
    44.                     }                    
    45.  
    46.                     Undo.RegisterCreatedObjectUndo(o, "created prefab");
    47.  
    48.                     Transform newT = o.transform;
    49.  
    50.                     if(t != null){                     
    51.  
    52.                         newT.position = t.position;
    53.                         newT.rotation = t.rotation;
    54.                         newT.localScale = t.localScale;
    55.                         newT.parent = t.parent;  
    56.                     }
    57.                 }
    58.  
    59.                 foreach (GameObject go in Selection.gameObjects) {
    60.  
    61.                     Undo.DestroyObjectImmediate(go);
    62.                 }
    63.             }
    64.         }
    65.     }
    66. }
    67.  
    By the way, there is a wiki for this (similar) script here:
    http://wiki.unity3d.com/index.php/ReplaceSelection
     
    Last edited: May 7, 2014
    Bakanovskiy95 and SAOTA like this.
  33. Meceka

    Meceka

    Joined:
    Dec 23, 2013
    Posts:
    423
    This is great, I wish I could see this script earlier. Thank you.
     
  34. Christopher Simon

    Christopher Simon

    Joined:
    Jun 28, 2014
    Posts:
    4
    Thank you guys so much! I'm loving this awesome script!
     
  35. Voronoi

    Voronoi

    Joined:
    Jul 2, 2012
    Posts:
    584
    Hey, this script saved me a ton of work. I fixed a bug where you are iterating over an array and destroying items, considered bad practice according to Unity Docs - http://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html

    It also just didn't work all the time. This explains why: http://answers.unity3d.com/questions/529044/why-is-iterating-an-array-and-destroying-objects-c.html

    So, using that as a guide, I have this working perfectly:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEditor;
    6.  
    7. public class BatchReplaceByName : ScriptableWizard
    8. {
    9.         public GameObject     m_newType;
    10.         public string         m_name = "";
    11.         public bool         m_matchCase = true;
    12.    
    13.         [MenuItem("Custom/Batch Replace By Name")]
    14.    
    15.         static void CreateWizard ()
    16.         {
    17.                 var replaceGameObjects = ScriptableWizard.DisplayWizard <BatchReplaceByName> ("Replace GameObjects", "Replace");
    18.                 replaceGameObjects.m_name = Selection.activeObject.name;                                                        //Prefill the name field with the active object
    19.  
    20.         }
    21.    
    22.         void OnWizardCreate ()
    23.         {
    24.                 GameObject[] allObjects = GameObject.FindObjectsOfType<GameObject> ();
    25.  
    26.                 List<GameObject> myList = new List<GameObject> ();
    27.  
    28.                 foreach (GameObject g in allObjects) {
    29.                         if ((m_matchCase ? g.name : g.name.ToUpper ()) == m_name) {
    30.                                 myList.Add (g);
    31.                         }
    32.                 }
    33.  
    34.                 if (!m_matchCase)
    35.                         m_name = m_name.ToUpper ();
    36.                
    37.                 for (int i = myList.Count-1; i >= 0; i--) {
    38.        
    39.                         GameObject newObject = (GameObject)PrefabUtility.InstantiatePrefab (m_newType);
    40.                         newObject.transform.parent = myList [i].transform.parent;
    41.                         newObject.transform.localPosition = myList [i].transform.localPosition;
    42.                         newObject.transform.localRotation = myList [i].transform.localRotation;
    43.                         newObject.transform.localScale = myList [i].transform.localScale;
    44.                         newObject.name = myList [i].name;
    45.                         UnityEngine.Object.DestroyImmediate (myList [i]);
    46.                         myList.RemoveAt (i);
    47.                 }
    48.  
    49.  
    50.         }
    51. }
    52.  
     
  36. Pulov

    Pulov

    Joined:
    Feb 20, 2010
    Posts:
    824
    Awesome script.

    I work in cad prorams so I place there the "prefabs" . I hope that now I can change these by a prefab and gain performance.
     
    Bysensa likes this.
  37. Xelnath

    Xelnath

    Joined:
    Jan 31, 2015
    Posts:
    402
    Can someone host this on GitHub already?
     
    filibis likes this.
  38. cadellinman

    cadellinman

    Joined:
    Dec 3, 2014
    Posts:
    16
    Thanks so much for the script, saved me a lot of time.
     
  39. cadellinman

    cadellinman

    Joined:
    Dec 3, 2014
    Posts:
    16
    Update from me- the API changed slightly for Unity 5 and this version should work with the new update. Anyone on Unity 4 or earlier will need the previous version.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4. // CopyComponents - by Michael L. Croswell for Colorado Game Coders, LLC
    5. // March 2010
    6. //Modified by Kristian Helle Jespersen
    7. //June 2011
    8. //Modified by Connor Cadellin McKee for Excamedia
    9. //April 2015
    10. public class ReplaceGameObjects : ScriptableWizard
    11. {
    12.     public bool copyValues = true;
    13.     public GameObject NewType;
    14.     public GameObject[] OldObjects;
    15.     [MenuItem("Custom/Replace GameObjects")]
    16.     static void CreateWizard()
    17.     {
    18.         var replaceGameObjects = ScriptableWizard.DisplayWizard <ReplaceGameObjects>("Replace GameObjects", "Replace");
    19.         replaceGameObjects.OldObjects = Selection.gameObjects;
    20.     }  
    21.     void OnWizardCreate()
    22.     {
    23.         //Transform[] Replaces;
    24.         //Replaces = Replace.GetComponentsInChildren<Transform>();      
    25.         foreach (GameObject go in OldObjects)
    26.         {
    27.             GameObject newObject;
    28.             newObject = (GameObject)PrefabUtility.InstantiatePrefab(NewType);
    29.             newObject.transform.parent = go.transform.parent;
    30.             newObject.transform.localPosition = go.transform.localPosition;
    31.             newObject.transform.localRotation = go.transform.localRotation;
    32.             newObject.transform.localScale = go.transform.localScale;          
    33.             DestroyImmediate(go);
    34.         }
    35.     }
    36. }
     
    Bakanovskiy95 and IgorAherne like this.
  40. fermmmm

    fermmmm

    Joined:
    Oct 18, 2013
    Posts:
    129
    I've improved it:
    - Fixed a warning message that was being fired.
    - Added an option to keep the original objects' name.
    - Improved field names and cleaned the code.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. // CopyComponents - by Michael L. Croswell for Colorado Game Coders, LLC
    4. // March 2010
    5. //Modified by Kristian Helle Jespersen
    6. //June 2011
    7. //Modified by Connor Cadellin McKee for Excamedia
    8. //April 2015
    9. //Modified by Fernando Medina (fermmmm)
    10. //April 2015
    11. public class ReplaceGameObjects : ScriptableWizard
    12. {
    13.     public GameObject Prefab;
    14.     public GameObject[] ObjectsToReplace;
    15.     public bool KeepOriginalNames = true;
    16.     [MenuItem("Custom/Replace GameObjects")]
    17.     static void CreateWizard()
    18.     {
    19.         var replaceGameObjects = DisplayWizard<ReplaceGameObjects>("Replace GameObjects", "Replace");
    20.         replaceGameObjects.ObjectsToReplace = Selection.gameObjects;
    21.     }
    22.     void OnWizardCreate()
    23.     {
    24.         foreach (GameObject go in ObjectsToReplace)
    25.         {
    26.             GameObject newObject;
    27.             newObject = (GameObject)PrefabUtility.InstantiatePrefab(Prefab);
    28.             newObject.transform.SetParent(go.transform.parent, true);
    29.             newObject.transform.localPosition = go.transform.localPosition;
    30.             newObject.transform.localRotation = go.transform.localRotation;
    31.             newObject.transform.localScale = go.transform.localScale;
    32.             if (KeepOriginalNames)
    33.                 newObject.transform.name = go.transform.name;
    34.             DestroyImmediate(go);
    35.         }
    36.     }
    37. }
     
    Last edited: Apr 23, 2015
  41. Alessandro-Previti

    Alessandro-Previti

    Joined:
    Nov 1, 2014
    Posts:
    30
    You all, are my heroes today.
    Thank you for sharing this, you saved hours of my life.
     
    MarshallVisions likes this.
  42. Elzean

    Elzean

    Joined:
    Nov 25, 2011
    Posts:
    584
    Hey,
    liked this scrip and i made my own version. I wanted to be able to have a preview of the result so i changed it back to an editor window. There is no more field to drag you prefab just selecting stuff should work.

    So click the "edit" button then select whatever objects in your scene, then go into your project view and select a prefab and it will appear in the scene view. If you are happy with the result you click the "apply" button in the bottom or "cancel". You can keep changing the scene selection or your prefab while in edit mode until you get what you want.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections.Generic;
    4. // CopyComponents - by Michael L. Croswell for Colorado Game Coders, LLC
    5. // March 2010
    6. //Modified by Kristian Helle Jespersen
    7. //June 2011
    8. //Modified by Connor Cadellin McKee for Excamedia
    9. //April 2015
    10. //Modified by Fernando Medina (fermmmm)
    11. //April 2015
    12. //Modified by Julien Tonsuso (www.julientonsuso.com)
    13. //July 2015
    14. //Changed into editor window and added instant preview in scene view
    15. public class ReplaceGameObjects : EditorWindow
    16. {
    17.     public GameObject Prefab;
    18.     public GameObject[] ObjectsToReplace;
    19.     public List<GameObject> TempObjects;
    20.     public bool KeepOriginalNames = true;
    21.     public bool EditMode = false;
    22.  
    23.  
    24.     // Add menu named "My Window" to the Window menu
    25.     [MenuItem("Window/ReplaceGameObjects")]
    26.     static void Init()
    27.     {
    28.         // Get existing open window or if none, make a new one:
    29.         ReplaceGameObjects window = (ReplaceGameObjects)EditorWindow.GetWindow(typeof(ReplaceGameObjects));
    30.      
    31.         window.Show();
    32.        
    33.     }
    34.  
    35.     void OnSelectionChange()
    36.     {
    37.  
    38.         GetSelection();
    39.         Repaint();
    40.     }
    41.  
    42.  
    43.     void OnGUI()
    44.     {
    45.         EditMode = GUILayout.Toggle(EditMode, "Edit");
    46.         if (GUI.changed)
    47.         {
    48.             if(EditMode)
    49.                 GetSelection();
    50.             else
    51.                 ResetPreview();
    52.         }
    53.         KeepOriginalNames = GUILayout.Toggle(KeepOriginalNames, "Keep names");
    54.         GUILayout.Space(5);
    55.         if (EditMode)
    56.         {
    57.             ResetPreview();
    58.  
    59.            
    60.             GUI.color = Color.yellow;
    61.             if (Prefab != null)
    62.             {
    63.                 GUILayout.Label("Prefab: ");
    64.                 GUILayout.Label(Prefab.name);
    65.             }else{
    66.                 GUILayout.Label("No prefab selected");
    67.             }
    68.             GUI.color = Color.white;
    69.            
    70.             GUILayout.Space(5);
    71.             GUILayout.BeginScrollView(new Vector2());
    72.             foreach (GameObject go in ObjectsToReplace)
    73.             {
    74.                 GUILayout.Label(go.name);
    75.  
    76.                 if (Prefab != null)
    77.                 {
    78.                     GameObject newObject;
    79.                     newObject = (GameObject)PrefabUtility.InstantiatePrefab(Prefab);
    80.                     newObject.transform.SetParent(go.transform.parent, true);
    81.                     newObject.transform.localPosition = go.transform.localPosition;
    82.                     newObject.transform.localRotation = go.transform.localRotation;
    83.                     newObject.transform.localScale = go.transform.localScale;
    84.                     TempObjects.Add(newObject);
    85.                     if (KeepOriginalNames)
    86.                         newObject.transform.name = go.transform.name;
    87.                     go.SetActive(false);
    88.                 }
    89.             }
    90.             GUILayout.EndScrollView();
    91.  
    92.             GUILayout.Space(5);
    93.  
    94.             GUILayout.BeginHorizontal();
    95.             if(GUILayout.Button("Apply"))
    96.             {
    97.                 foreach (GameObject go in ObjectsToReplace)
    98.                 {
    99.                     DestroyImmediate(go);
    100.                 }
    101.                 EditMode = false;
    102.             };
    103.  
    104.             if (GUILayout.Button("Cancel"))
    105.             {
    106.                 ResetPreview();
    107.                 EditMode = false;
    108.             };
    109.             GUILayout.EndHorizontal();
    110.         }
    111.         else
    112.         {
    113.             ObjectsToReplace = new GameObject[0];
    114.             TempObjects.Clear();
    115.             Prefab = null;
    116.         }
    117.        
    118.     }
    119.  
    120.  
    121.     void OnDestroy()
    122.     {
    123.         ResetPreview();
    124.     }
    125.  
    126.  
    127.     void GetSelection()
    128.     {
    129.         if (EditMode && Selection.activeGameObject != null)
    130.         {
    131.             PrefabType t = PrefabUtility.GetPrefabType(Selection.activeGameObject);
    132.             if (t == PrefabType.None || t == PrefabType.PrefabInstance)
    133.             {
    134.                 ResetPreview();
    135.                 ObjectsToReplace = Selection.gameObjects;
    136.             }
    137.             else if (t == PrefabType.Prefab)
    138.             {
    139.                 Prefab = Selection.activeGameObject;
    140.             }
    141.  
    142.         }
    143.     }
    144.  
    145.  
    146.     void ResetPreview()
    147.     {
    148.         if (TempObjects != null)
    149.         {
    150.             foreach (GameObject go in TempObjects)
    151.             {
    152.                 DestroyImmediate(go);
    153.             }
    154.         }
    155.  
    156.         foreach (GameObject go in ObjectsToReplace)
    157.         {
    158.             go.SetActive(true);
    159.         }
    160.  
    161.         TempObjects.Clear();
    162.     }
    163. }

    What woould be nice is adding an undo/redo system and making it look better :p

    It's best you give it a try first just make sure there is no bugs(seems fine in my project).
     
    Bakanovskiy95 and Rodolfo-Rubens like this.
  43. VesuvianPrime

    VesuvianPrime

    Joined:
    Feb 26, 2013
    Posts:
    135
    Needed to do this today as well, found this thread, got OCD and rewrote @Elzean's solution:



    Bitbucket link
     
    Last edited: Aug 18, 2015
    Bakanovskiy95 and Rodolfo-Rubens like this.
  44. Elzean

    Elzean

    Joined:
    Nov 25, 2011
    Posts:
    584
    I will try later i can't from where i am now, but from seeing the code you removed the preview in editor right ?
    I don't know if you tried what i did but there is also the fact that i could just click prefabs inside the project window without dragging them in the field. May be i missed something in your code though :p

    Otherwise seems nice :)
     
  45. VesuvianPrime

    VesuvianPrime

    Joined:
    Feb 26, 2013
    Posts:
    135
    I removed the preview and added Undo/Redo functionality. Personally I find the object-field for the prefab to be far more intuitive (you can always hit the little dot and open a selection window), but I can see how that would be very subjective.

    It is nice, it's mostly your work! I just streamlined it for my own needs.

    Oh, actually, a big advantage in this version is the prefab instance copies the sibling index of the original. In my example with 100+ collectables, the order was originally getting garbled by the selection array.
     
    Last edited: Aug 18, 2015
    fermmmm likes this.
  46. Erikoinen

    Erikoinen

    Joined:
    Nov 10, 2014
    Posts:
    68
    So many thank yous to you guys, the script is awesome!
     
  47. wav

    wav

    Joined:
    Dec 7, 2011
    Posts:
    4
    Just wanted to say that I <3 you all! :D
     
  48. MarkusR

    MarkusR

    Joined:
    Jan 12, 2015
    Posts:
    1
    thanks all for providing this replace script :)
     
  49. DDelapena

    DDelapena

    Joined:
    May 3, 2013
    Posts:
    6
    This is great, thanks guys.
     
  50. skudgee

    skudgee

    Joined:
    Jun 17, 2015
    Posts:
    5
    Just found your amazing script ! Save hours of manual replacement, many thanks !
    This should be an native tool.