Skip to content

Instantly share code, notes, and snippets.

@NickDiMucci
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickDiMucci/207307e60ef53155d760 to your computer and use it in GitHub Desktop.
Save NickDiMucci/207307e60ef53155d760 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class UnityBulkReplaceTool : MonoBehaviour
{
public GameObject objectToReplace = null;
public GameObject objectToSpawn = null;
[MenuItem("Window/Video Game/Bulk Replacer", false, vgMath.vgWindowPriority)]
void Start()
{
// Get existing open window or if none, make a new one:
EditorWindow.GetWindow(typeof(vgBulkReplaceWindow));
}
void OnGUI()
{
EditorGUILayout.BeginVertical();
objectToReplace = (GameObject)EditorGUILayout.ObjectField("Object To Replace:", objectToReplace, typeof(GameObject), true);
objectToSpawn = (GameObject)EditorGUILayout.ObjectField("Prefab To Spawn:", objectToSpawn, typeof(GameObject), true);
if( objectToReplace != null )
{
GameObject[] selectedObjects = GameObject.FindObjectsOfType<GameObject>();
List<GameObject> objectList = new List<GameObject>();
for( int i = 0; i < selectedObjects.Length; ++i )
{
GameObject testObject = selectedObjects[i];
if( testObject.name == objectToReplace.name )
{
objectList.Add(selectedObjects[i]);
}
}
Selection.objects = objectList.ToArray();
if( GUILayout.Button(new GUIContent("Replace All Objects", "Replaces all objects with selected prefab")) )
{
foreach( GameObject go in objectList )
{
GameObject newObject;
newObject = PrefabUtility.InstantiatePrefab(objectToSpawn) as GameObject;
if( newObject == null )
{
Debug.LogError("objectToSpawn is not a prefab!", newObject);
break;
}
newObject.transform.position = go.transform.position;
newObject.transform.rotation = go.transform.rotation;
newObject.transform.parent = go.transform.parent;
Undo.RegisterCreatedObjectUndo(newObject, "Bulk replaced");
Undo.DestroyObjectImmediate(go);
}
}
}
else
{
GreyedOutButton("Replace All Objects", "Must select object to replace");
}
if( GUILayout.Button("Clear") )
{
objectToReplace = null;
objectToSpawn = null;
}
EditorGUILayout.EndVertical();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment