Saturday, February 4, 2012

Batch replace gameobjects in Unity

When creating Harry the Fairy, we often found ourselves having to replace hundreds of prefab instances so I created this little script. It replaces a number of gameobjects with another and gives you the possibility to save all the transform values i.e. position, rotation and scale.

C# Script must be placed in "editor" folder.
using UnityEngine;
using UnityEditor;
using System.Collections;

public class ReplaceGameObjects : ScriptableWizard
{
    public bool copyValues = true;
    public GameObject NewType;
    public GameObject[] OldObjects;

    [MenuItem("Custom/Replace GameObjects")]


    static void CreateWizard()
    {
        ScriptableWizard.DisplayWizard("Replace GameObjects", typeof(ReplaceGameObjects), "Replace");
    }

    void OnWizardCreate()
    {
        foreach (GameObject go in OldObjects)
        {
            GameObject newObject;
            newObject = (GameObject)EditorUtility.InstantiatePrefab(NewType);
            newObject.transform.position = go.transform.position;
            newObject.transform.rotation = go.transform.rotation;
            newObject.transform.parent = go.transform.parent;

            DestroyImmediate(go);

        }

    }
}

Here's a visual walkthrough:

Go into Custom ->Replace Gameobjects


Select any number of gameobjects and drag them into "Old Objects".
Then, from the project pane, drag the gameobject that you want to replace with into "New Type".


Press "Replace"


Enjoy :)

/Kristian
And credits to Michael L. Croswell

8 comments:

  1. Thanks for the script, very handy! You might want to mention that this should be a .cs script and that the script needs the following at the top for it to work:

    using UnityEngine;
    using UnityEditor;
    using System.Collections;

    Thanks again!

    ReplyDelete
  2. Hi Timzilla

    True, thanks for the feedback.
    Correction has been made.

    ReplyDelete
  3. Thanks for sharing this! It pays off even when replacing a single object (because of the transform preservation). Awesome!

    ReplyDelete
  4. newObject.transform.parent = go.transform.parent;

    Will go wrong i guess if 'go' is also an object to be replaced?
    Say A and B will be replaced but B is also a parent of A.
    Then A.parent will reference a null object after the script has run.

    ReplyDelete
  5. Thank you very much! This is quite a time saver. I wish I found this a lot sooner.

    ReplyDelete
  6. Thanks mate you saved me a lot of time =)

    ReplyDelete