Last active
February 25, 2021 14:35
-
-
Save jfranmora/6f45f1bf33a6d5622369bf18015a8603 to your computer and use it in GitHub Desktop.
Utility to change the target script of a component
This file contains hidden or 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
using UnityEditor; | |
using UnityEngine; | |
public static class EditorUtils | |
{ | |
/// <summary> | |
/// Verify whether it can be converted to the specified component. | |
/// </summary> | |
public static bool CanConvertTo<T>(Object context) where T : MonoBehaviour | |
{ | |
return context && context.GetType() != typeof(T); | |
} | |
/// <summary> | |
/// Convert to the specified component. | |
/// </summary> | |
public static void ConvertTo<T>(Object context) where T : MonoBehaviour | |
{ | |
var target = context as MonoBehaviour; | |
var so = new SerializedObject(target); | |
so.Update(); | |
var 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment