Skip to content

Instantly share code, notes, and snippets.

@LaserKaspar
Created November 4, 2021 20:37
Show Gist options
  • Save LaserKaspar/1710aded4bfcc8748e0b01062d375d6c to your computer and use it in GitHub Desktop.
Save LaserKaspar/1710aded4bfcc8748e0b01062d375d6c to your computer and use it in GitHub Desktop.
(UnityEngine) Replaces object with specified prefab (Keeps transform). Useful for prototyping.
using UnityEngine;
using UnityEditor;
public class ReplaceWithPrefab : EditorWindow
{
[SerializeField] private int lenght;
public int Lenght
{
get => lenght;
set
{
lenght = value;
if (value != 0)
{
GameObject[] buffer = _gameObjects;
_gameObjects = new GameObject[lenght];
for (int i = 0; i < lenght; i++)
{
if (buffer.Length > i)
_gameObjects[i] = buffer[i];
else
_gameObjects[i] = null;
}
}
}
}
private GameObject[] _gameObjects;
[MenuItem("Tools/Replace With Prefab")]
static void CreateReplaceWithPrefab()
{
EditorWindow.GetWindow<ReplaceWithPrefab>();
}
private void OnGUI()
{
Lenght = EditorGUILayout.IntField("Prefab count: ", Lenght);
for (int j = 0; j < Lenght; j++)
{
GUILayout.BeginHorizontal();
_gameObjects[j] = (GameObject)EditorGUILayout.ObjectField(_gameObjects[j], typeof(GameObject), false);
if (GUILayout.Button("Replace"))
{
var selection = Selection.gameObjects;
for (var i = selection.Length - 1; i >= 0; --i)
{
var selected = selection[i];
GameObject newObject;
if (PrefabUtility.IsPartOfPrefabAsset(_gameObjects[j]))
{
newObject = (GameObject)PrefabUtility.InstantiatePrefab(_gameObjects[j]);
}
else
{
newObject = Instantiate(_gameObjects[j]);
newObject.name = _gameObjects[j].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);
}
}
GUILayout.EndHorizontal();
}
GUI.enabled = false;
EditorGUILayout.LabelField("Selection count: " + Selection.objects.Length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment