GameVsJam/3d Prototyp/Assets/Editor/ReplaceWithPrefab.cs

66 lines
2.3 KiB
C#
Raw Normal View History

2024-04-06 01:18:12 +02:00
using UnityEditor;
2024-04-07 14:17:09 +02:00
using UnityEngine;
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
namespace GameVsJam.Editor
2024-04-06 01:18:12 +02:00
{
2024-04-07 14:17:09 +02:00
public class ReplaceWithPrefab : EditorWindow
2024-04-06 01:18:12 +02:00
{
2024-04-07 14:17:09 +02:00
[SerializeField] private GameObject prefab;
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
[MenuItem("Tools/Replace With Prefab")]
static void CreateReplaceWithPrefab()
{
ReplaceWithPrefab v = EditorWindow.GetWindow<ReplaceWithPrefab>();
}
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
private void OnGUI()
2024-04-06 01:18:12 +02:00
{
2024-04-07 14:17:09 +02:00
prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
if (GUILayout.Button("Replace"))
2024-04-06 01:18:12 +02:00
{
2024-04-07 14:17:09 +02:00
var selection = Selection.gameObjects;
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
for (var i = selection.Length - 1; i >= 0; --i)
2024-04-06 01:18:12 +02:00
{
2024-04-07 14:17:09 +02:00
var selected = selection[i];
var prefabType = PrefabUtility.GetPrefabType(prefab);
GameObject newObject;
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
if (prefabType == PrefabType.Prefab)
{
newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
}
else
{
newObject = Instantiate(prefab);
newObject.name = prefab.name;
}
2024-04-06 01:18:12 +02:00
2024-04-07 14:17:09 +02:00
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);
}
2024-04-06 01:18:12 +02:00
}
2024-04-07 14:17:09 +02:00
GUI.enabled = false;
EditorGUILayout.LabelField("Selection count: " + Selection.objects.Length);
2024-04-06 01:18:12 +02:00
}
2024-04-07 14:17:09 +02:00
// private void OnLostFocus() {
// GetWindow<ReplaceWithPrefab>().Close();
// }
2024-04-06 01:18:12 +02:00
}
}