Skip to content

Instantly share code, notes, and snippets.

@rondreas rondreas/Replacer.cs

Created Oct 10, 2018
What would you like to do?
Unity Editor Tool to attempt replace selected GameObjects with any asset matching the name of selected.
using UnityEngine;
using UnityEditor;
public class Replacer : EditorWindow
public static void ShowWindow()
EditorWindow.GetWindow<Replacer>("Replace GameObject");
private void OnGUI()
{ = true;
string instructions = "Select GameObjects to be replaced, script will go through each selected " +
" GameObject and check it is active in Hierarchy, then find path to the asset and instansiate " +
"it - set Transform and Parent to be same as selection and destroy the old one.\n\n" +
"Known issues; \n\n" +
" - Only works if GameObject hasn't been renamed.\n";
GUILayout.Label("Instructions", EditorStyles.boldLabel);
if (GUILayout.Button("Replace Selected GameObjects"))
GameObject[] selection = Selection.gameObjects;
foreach (GameObject item in selection)
if (item.activeInHierarchy)
// TODO: Refactor so we can avoid this nested chaos.
// TODO: Solve path to renamed GameObjects
string[] guids = AssetDatabase.FindAssets(GetObjectName(;
if (guids.Length > 0)
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
GameObject asset = Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(path));
Replace(item, asset);
/// <summary>
/// Splits a string on spaces and return first string in resulting string array.
/// </summary>
/// <param name="NameInHierarchy"></param>
/// <returns></returns>
private string GetObjectName(string NameInHierarchy) {
return NameInHierarchy.Split(' ')[0];
/// <summary>
/// Replace oldGameObject with newGameObject, copying over transform information
/// and name.
/// </summary>
/// <param name="oldGameObject"></param>
/// <param name="newGameObject"></param>
private void Replace(GameObject oldGameObject, GameObject newGameObject)
newGameObject.transform.parent = oldGameObject.transform.parent;
newGameObject.transform.localScale = oldGameObject.transform.localScale;
string name =;
DestroyImmediate(oldGameObject); = name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.