-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathUnityObjectEx.cs
98 lines (75 loc) · 2.9 KB
/
UnityObjectEx.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
86
87
88
89
90
91
92
93
94
95
96
97
98
//Create: Icarus
//ヾ(•ω•`)o
//2020-10-08 08:26
//Icarus.EditorFrame
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace CabinIcarus.EditorFrame.Utils
{
public static class UnityObjectEx
{
private static MonoScript[] _monoScripts;
[InitializeOnLoadMethod]
static void _init()
{
_monoScripts = MonoImporter.GetAllRuntimeMonoScripts();
}
// public static void AddReplaceContextMenu(Type source,Type target,Action<Component> onReplace)
// {
// var menuPath = $"CONTEXT/{source.Name}/Replace {target.Name}";
// Debug.LogError(menuPath);
// ProjectMenu.AddMenu(menuPath,100, _menu);
// EditorUtility.SelectMenuItemFunction
// }
public static T ReplaceComponent<T>(this Component self) where T : Component
{
return self.ReplaceComponent(typeof(T)) as T;
}
public static Component ReplaceComponent(this Component self, Type type)
{
if (!typeof(Component).IsAssignableFrom(type) || self.GetType() == type)
{
return null;
}
var index = Undo.GetCurrentGroup();
Undo.SetCurrentGroupName($"{self.GetType().Name} Replace To {type.Name}");
var go = self.gameObject;
if (PrefabUtility.IsPartOfPrefabInstance(go))
{
PrefabUtility.ApplyPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(go),InteractionMode.AutomatedAction);
Undo.DestroyObjectImmediate(self);
var c = Undo.AddComponent(go, type);
Undo.CollapseUndoOperations(index + 1);
var removeC = PrefabUtility.GetRemovedComponents(go);
EditorUtility.CopySerializedManagedFieldsOnly(removeC.Last().assetComponent, c);
return c;
}
var serobj = new SerializedObject(self);
MonoScript newMono = null;
foreach (var monoScript in _monoScripts)
{
if (monoScript == null)
{
_init();
return ReplaceComponent(self, type);
}
if (monoScript.GetClass() == type)
{
newMono = monoScript;
break;
}
}
if (newMono == null)
{
return null;
}
var property = serobj.FindProperty("m_Script");
property.objectReferenceValue = newMono;
serobj.ApplyModifiedProperties();
serobj.Update();
return (Component) serobj.targetObject;
}
}
}