Add RequireInterface attribute

This commit is contained in:
Hubert Mattusch 2022-09-13 22:41:19 +02:00
parent 6c6ef9ad0d
commit 51223864a6
6 changed files with 79 additions and 0 deletions

8
RequireInterface.meta Normal file
View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: da80835a1611a5e4d908f51f09e8d3bc
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 849242dbc213969488426f85222a43a9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,41 @@
using UnityEngine;
using UnityEditor;
/// <summary>
/// Drawer for the RequireInterface attribute.
/// </summary>
[CustomPropertyDrawer(typeof(RequireInterfaceAttribute))]
public class RequireInterfaceDrawer : PropertyDrawer
{
/// <summary>
/// Overrides GUI drawing for the attribute.
/// </summary>
/// <param name="position">Position.</param>
/// <param name="property">Property.</param>
/// <param name="label">Label.</param>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Check if this is reference type property.
if (property.propertyType == SerializedPropertyType.ObjectReference)
{
// Get attribute parameters.
var requiredAttribute = this.attribute as RequireInterfaceAttribute;
// Begin drawing property field.
EditorGUI.BeginProperty(position, label, property);
// Draw property field.
property.objectReferenceValue = EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.requiredType, true);
// Finish drawing property field.
EditorGUI.EndProperty();
}
else
{
// If field is not reference, show error message.
// Save previous color and change GUI to red.
var previousColor = GUI.color;
GUI.color = Color.red;
// Display label with error message.
EditorGUI.LabelField(position, label, new GUIContent("Property is not a reference type"));
// Revert color change.
GUI.color = previousColor;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b430a75a32f8e534f8661d364d842691
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 29f2a6e637914fe4292225071a7c5157
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: