Created
November 29, 2017 02:19
-
-
Save mob-sakai/0a31db3582c5c2bda587916e03028a3e to your computer and use it in GitHub Desktop.
Component converter for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if UNITY_EDITOR | |
using UnityEngine; | |
using UnityEditor; | |
/// <summary> | |
/// Component converter for editor. | |
/// </summary> | |
public static class ComponentConverter | |
{ | |
//%%%% v Context menu for editor v %%%% | |
[MenuItem("CONTEXT/Graphic/Convert To Image", true)] | |
static bool _ConvertToButtonEx(MenuCommand command) | |
{ | |
return CanConvertTo<UnityEngine.UI.Image>(command.context); | |
} | |
[MenuItem("CONTEXT/Button/Convert To Image", false)] | |
static void ConvertToButtonEx(MenuCommand command) | |
{ | |
ConvertTo<UnityEngine.UI.Image>(command.context); | |
} | |
[MenuItem("CONTEXT/Button/Convert To RawImage", true)] | |
static bool _ConvertToButton(MenuCommand command) | |
{ | |
return CanConvertTo<UnityEngine.UI.RawImage>(command.context); | |
} | |
[MenuItem("CONTEXT/Button/Convert To RawImage", false)] | |
static void ConvertToButton(MenuCommand command) | |
{ | |
ConvertTo<UnityEngine.UI.RawImage>(command.context); | |
} | |
//%%%% ^ Context menu for editor ^ %%%% | |
/// <summary> | |
/// Verify whether it can be converted to the specified component. | |
/// </summary> | |
protected static bool CanConvertTo<T>(Object context) where T : MonoBehaviour | |
{ | |
return context && context.GetType() != typeof(T); | |
} | |
/// <summary> | |
/// Convert to the specified component. | |
/// </summary> | |
protected static void ConvertTo<T>(Object context) where T : MonoBehaviour | |
{ | |
var target = context as MonoBehaviour; | |
var so = new SerializedObject(target); | |
so.Update(); | |
bool oldEnable = target.enabled; | |
target.enabled = false; | |
// Find MonoScript of the specified component. | |
foreach (var script in Resources.FindObjectsOfTypeAll<MonoScript>()) | |
{ | |
if (script.GetClass() != typeof(T)) | |
continue; | |
// Set 'm_Script' to convert. | |
so.FindProperty("m_Script").objectReferenceValue = script; | |
so.ApplyModifiedProperties(); | |
break; | |
} | |
(so.targetObject as MonoBehaviour).enabled = oldEnable; | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment