/
ReplaceWithPrefab.cs
85 lines (69 loc) · 2.96 KB
/
ReplaceWithPrefab.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using UnityEditor;
using UnityEngine;
namespace Chimp.Editor
{
internal class ReplaceWithPrefab : EditorWindow
{
[SerializeField] private GameObject _Prefab;
[SerializeField] private bool _ApplyRotation = true;
[SerializeField] private bool _ApplyScale = true;
[MenuItem("Chimp/Editor/Replace With Prefab %q", false, 200)]
private static void CreateReplaceWithPrefab()
{
var window = GetWindow<ReplaceWithPrefab>();
window.titleContent = new GUIContent("Replace with Prefab");
window.minSize = new Vector2(370, 150);
window.Show();
}
private void OnGUI()
{
GUILayout.BeginVertical();
GUILayout.Space(8);
_Prefab = (GameObject) EditorGUILayout.ObjectField("Prefab", _Prefab, typeof(GameObject), false);
_ApplyRotation = EditorGUILayout.Toggle("Apply Rotation", _ApplyRotation);
_ApplyScale = EditorGUILayout.Toggle("Apply Scale", _ApplyScale);
GUILayout.FlexibleSpace();
GUI.enabled = false;
EditorGUILayout.LabelField("Selection count: " + Selection.objects.Length);
GUI.enabled = true;
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Replace", GUILayout.MinHeight(50)))
{
GameObject[] selection = Selection.gameObjects;
for (int i = selection.Length - 1; i >= 0; --i)
{
GameObject selected = selection[i];
GameObject newObject;
if (PrefabUtility.IsPartOfPrefabAsset(_Prefab))
{
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;
if (_ApplyRotation)
{
newObject.transform.localRotation = selected.transform.localRotation;
}
if (_ApplyScale)
{
newObject.transform.localScale = selected.transform.localScale;
}
newObject.transform.SetSiblingIndex(selected.transform.GetSiblingIndex());
Undo.DestroyObjectImmediate(selected);
}
}
GUILayout.EndVertical();
}
}
}