Skip to content

Instantly share code, notes, and snippets.

@acoppes
Created December 30, 2022 19:57
Show Gist options
  • Save acoppes/2ef6b89ca7d9f27461eb54ac816323ff to your computer and use it in GitHub Desktop.
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
[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