Skip to content

Instantly share code, notes, and snippets.

@PixelEnvision
Created February 7, 2023 11:58
Show Gist options
  • Save PixelEnvision/3801212d47eee92d06507ff07110d540 to your computer and use it in GitHub Desktop.
Save PixelEnvision/3801212d47eee92d06507ff07110d540 to your computer and use it in GitHub Desktop.
Tool to replace multiple game objects or prefabs with a different prefab, drop in "Editor" folder.
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
public class ReplaceWithPrefab : EditorWindow
{
[SerializeField] private GameObject prefab;
[MenuItem("Tools/Replace With Prefab")]
static void CreateReplaceWithPrefab()
{
EditorWindow.GetWindow<ReplaceWithPrefab>();
}
private void OnGUI()
{
prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);
if (GUILayout.Button("Replace"))
{
var selection = Selection.gameObjects;
for (var i = selection.Length - 1; i >= 0; --i)
{
var selected = selection[i];
var prefabType = PrefabUtility.GetPrefabAssetType(prefab);
GameObject newObject;
if (prefabType != PrefabAssetType.NotAPrefab)
{
newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
}
else
{
newObject = Instantiate(prefab);
newObject.name = prefab.name;
}
if (newObject == null)
{
Debug.LogError("Error instantiating prefab");
break;
}
Undo.RegisterCreatedObjectUndo(newObject, "Replace With Prefabs");
newObject.transform.parent = selected.transform.parent;
newObject.transform.localPosition = selected.transform.localPosition;
newObject.transform.localRotation = selected.transform.localRotation;
newObject.transform.localScale = selected.transform.localScale;
newObject.transform.SetSiblingIndex(selected.transform.GetSiblingIndex());
Undo.DestroyObjectImmediate(selected);
}
}
GUI.enabled = false;
EditorGUILayout.LabelField("Selection count: " + Selection.objects.Length);
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment