Skip to content

Instantly share code, notes, and snippets.

@TsubameUnity
Last active November 8, 2019 07:04
Show Gist options
  • Save TsubameUnity/28ea55aa789f0a23420ebaf77cc29438 to your computer and use it in GitHub Desktop.
Save TsubameUnity/28ea55aa789f0a23420ebaf77cc29438 to your computer and use it in GitHub Desktop.
ボタンを操作できるようにラップしたもの。スクリプトを追加すれば[UI/Button]を呼び出したのと同等の処理を行う。
using UnityEngine;
using UnityEngine.UI;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UI;
using UnityEditor.SceneManagement;
#endif
public class ButtonTextCustomer : Button, IControlText
{
[SerializeField] Text _text;
public void ChangeTextColor(Color color) => _text.color = color;
#if UNITY_EDITOR
[CustomEditor(typeof(ButtonTextCustomer))]
class ButtonTextCustomerCustom : ButtonEditor
{
ButtonTextCustomer _handle;
protected override void OnEnable()
{
base.OnEnable();
_handle = target as ButtonTextCustomer;
if (!_handle._text)
{
var text = _handle.GetComponentInChildren<Text>(true);
if (!text)
{
// UnityEditor.EditorApplication.ExecuteMenuItemWithTemporaryContext(string menuItemPath, UnityEngine.Object[] objects) を呼び出す
var flag = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
var editorAppType = typeof(EditorApplication);
var uiMenuItemMethod = editorAppType.GetMethod("ExecuteMenuItemWithTemporaryContext", flag);
uiMenuItemMethod.Invoke(null, new object[] { "GameObject/UI/Text", new Object[] { _handle.gameObject } });
// 上記実行後に生成されたTextへフォーカスが移るので、それを取得する
text = Selection.activeTransform.GetComponent<Text>();
Selection.activeTransform = Selection.activeTransform.parent;
}
_handle._text = text;
EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
}
}
public override void OnInspectorGUI()
{
_handle._text = (Text)EditorGUILayout.ObjectField("Text", _handle._text, typeof(Text), true);
base.OnInspectorGUI();
}
}
#endif
}
interface IControlText
{
void ChangeTextColor(Color color);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment