Created
December 30, 2022 19:57
-
-
Save acoppes/2ef6b89ca7d9f27461eb54ac816323ff to your computer and use it in GitHub Desktop.
Useful to validate if references to Object or GameObject match specific type in Unity
This file contains 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
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class)] | |
public class TypeValidationAttribute : PropertyAttribute | |
{ | |
public Type typeToValidate; | |
public TypeValidationAttribute(Type typeToValidate) | |
{ | |
this.typeToValidate = typeToValidate; | |
} | |
} | |
[CustomPropertyDrawer(typeof(TypeValidationAttribute), true)] | |
public class TypeValidationPropertyDrawer: PropertyDrawer | |
{ | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
if (property.propertyType != SerializedPropertyType.ObjectReference) | |
{ | |
EditorGUI.LabelField(position, $"Invalid usage of TypeValidation for field \"{label.text}\", use with Object references."); | |
return; | |
} | |
var typeToValidate = (attribute as TypeValidationAttribute).typeToValidate; | |
EditorGUI.BeginChangeCheck(); | |
EditorGUI.ObjectField(position, property, label); | |
if (EditorGUI.EndChangeCheck()) | |
{ | |
var referencedObject = property.objectReferenceValue; | |
if (typeToValidate.IsInstanceOfType(referencedObject)) | |
{ | |
return; | |
} | |
if (referencedObject is GameObject gameObject) | |
{ | |
var isValidType = gameObject.GetComponentInChildren(typeToValidate) != null; | |
if (!isValidType) | |
{ | |
property.objectReferenceValue = null; | |
Debug.Log($"Invalid object, not an {typeToValidate.Name}."); | |
} | |
} | |
else | |
{ | |
property.objectReferenceValue = null; | |
Debug.Log($"Invalid object, not an {typeToValidate.Name}."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment