主にプログラミング関連のメモ帳 ♪(✿╹ヮ╹)ノ
書いてあるコードは自己責任でご自由にどうぞ。記事本文の無断転載は禁止です。
2020/11/20
そんなことをする必要があるかどうかはさておき、やりたくなったので。
ということでいつもの前提環境
といっても、実装は簡単で、こんな感じ。
もしかしたらこんなことしなくても良いカモだけど。
[SerializeField]
[UdonBehaviour(typeof(CustomUSharpComponent))]
private UdonBehaviour _behaviour;
//
private void OnGUI()
{
var so = new SerializedObject(this);
so.Update();
EditorGUILayout.PropertyField(so.FindProperty(nameof(_behaviour)));
so.ApplyModifiedProperties();
}
[AttributeUsage(AttributeTargets.Field)]
internal class UdonBehaviourAttribute : PropertyAttribute
{
public Type Type { get; }
public UdonBehaviourAttribute(Type t)
{
this.Type = t;
}
}
[CustomPropertyDrawer(typeof(UdonBehaviourAttribute))]
internal class UdonBehaviourDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.objectReferenceValue != null)
{
var behaviour = property.objectReferenceValue as UdonBehaviour;
if (!IsValidUdonSharpProgram(attribute as UdonBehaviourAttribute, behaviour))
property.objectReferenceValue = null;
}
EditorGUI.PropertyField(position, property, label);
}
private static bool IsValidUdonSharpProgram(UdonBehaviourAttribute attr, UdonBehaviour behaviour)
{
return UdonSharpProgramAsset.GetBehaviourClass(behaviour) == attr.Type;
}
}
UdonBehaviour
にくっついている U# クラスは UdonSharpProgramAsset#GetBehaviourClass
から取れるので、
そこで型を比較して上げれば OK。
ということでメモでした。