Как узнать унаследован ли от интерфейса MonoScript Unity
У меня есть код для проверки MonoBehaviour.
private void CheckMonoBehaviour(SerializedProperty property, Type targetType)
{
MonoBehaviour field = property.objectReferenceValue as MonoBehaviour;
Type fieldType = field.GetType();
if (targetType.IsAssignableFrom(fieldType) == false)
{
property.objectReferenceValue = null;
Debug.LogError("MonoBehaviour must implement " + targetType + " interface");
}
}
Я решил использовать этот код для MonoScript. Но он стал проходить через if даже если я знал что этот скрипт наследуется от нужного интерфейса. В дебаге я увидел, что когда я использую MonoBehaviour то Type у меня был {Gun}(Класс который наследуется от нужного мне интерфейса), а в MonoScript у меня было {UnityEditor.MonoScript}. Объясните пожалуйста как это происходит и как это решить.
Ответы (1 шт):
Автор решения: Yaroslav
→ Ссылка
Из учебного проекта Karting Microgame
using System;
using UnityEngine;
/// <summary>
/// An attribute that forces a public field to implement an interface.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public sealed class RequireInterfaceAttribute : PropertyAttribute
{
public readonly Type type;
public RequireInterfaceAttribute(Type value)
{
if (!value.IsInterface)
{
throw new Exception("Type must be an interface!");
}
type = value;
}
}
using System;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
/// <summary>
/// A drawer for an attribute that forces a public field to implement an interface.
/// </summary>
[CustomPropertyDrawer(typeof (RequireInterfaceAttribute))]
sealed class RequireInterfaceAttributeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.propertyType != SerializedPropertyType.ObjectReference)
{
Debug.LogError("RequireInterfaceAttribute can only be used on fields of type UnityEngine.Object or one of its subclasses!");
return;
}
Object propertyObject = property.objectReferenceValue;
if (propertyObject != null)
{
Type interfaceType = ((RequireInterfaceAttribute)attribute).type;
Type propertyType = propertyObject.GetType ();
if (propertyType.IsAssignableFrom (interfaceType))
{
Debug.LogError (propertyObject + " does not implement " + interfaceType.Name);
property.objectReferenceValue = null;
}
}
EditorGUI.PropertyField(position, property, label);
if (property.objectReferenceValue is GameObject)
property.objectReferenceValue = ((GameObject)property.objectReferenceValue).GetComponent (((RequireInterfaceAttribute)attribute).type);
}
}