Skip to content

Instantly share code, notes, and snippets.

@rondreas
Created October 10, 2018 11:44
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 rondreas/bf3e04e3c095ed72b30577bb00b425ee to your computer and use it in GitHub Desktop.
Save rondreas/bf3e04e3c095ed72b30577bb00b425ee to your computer and use it in GitHub Desktop.
Unity Editor Tool to attempt replace selected GameObjects with any asset matching the name of selected.
using UnityEngine;
using UnityEditor;
public class Replacer : EditorWindow
{
[MenuItem("Window/Replacer")]
public static void ShowWindow()
{
EditorWindow.GetWindow<Replacer>("Replace GameObject");
}
private void OnGUI()
{
GUI.skin.label.wordWrap = 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);
GUILayout.Label(instructions);
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(item.name));
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.SetPositionAndRotation(
oldGameObject.transform.position,
oldGameObject.transform.rotation
);
newGameObject.transform.localScale = oldGameObject.transform.localScale;
string name = oldGameObject.name;
DestroyImmediate(oldGameObject);
newGameObject.name = name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment