Created
April 12, 2017 19:11
-
-
Save ericdrobinson/bb360be75c83b4a2bf42723d9b710a11 to your computer and use it in GitHub Desktop.
Mark a Field as Required 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
using System; | |
using UnityEngine; | |
[AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] | |
public class RequireReferenceAttribute : PropertyAttribute | |
{ | |
public readonly Color highlight; | |
public RequireReferenceAttribute() | |
{ | |
// Red, but not blow-your-eyes-out red. | |
highlight = new Color(1f, 0f, 0f, 0.75f); | |
} | |
public RequireReferenceAttribute(float r, float g, float b, float a = 0.75f) | |
{ | |
highlight = new Color(r, g, b, a); | |
} | |
} |
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
using UnityEditor; | |
using UnityEngine; | |
[CustomPropertyDrawer(typeof(RequireReferenceAttribute))] | |
public class RequireReferenceDrawer : PropertyDrawer | |
{ | |
bool bDidShowError = false; | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
if (property.propertyType != SerializedPropertyType.ObjectReference) | |
{ | |
if (!bDidShowError) | |
{ | |
string errorStr = string.Format("The [RequireReference] attribute must be used with an object reference. See the '{0}' field on object '{1}'.", property.displayName, property.serializedObject.targetObject.name); | |
Debug.LogError(errorStr); | |
bDidShowError = true; | |
} | |
} | |
else if (property.objectReferenceValue == null) | |
{ | |
Color originalColor = GUI.color; | |
Rect labelPos = position; | |
labelPos.xMax = labelPos.xMin + EditorGUIUtility.labelWidth; | |
RequireReferenceAttribute requireAttribute = (RequireReferenceAttribute)base.attribute; | |
GUI.color = requireAttribute.highlight; | |
GUI.Box(labelPos, string.Empty); | |
GUI.color = originalColor; | |
} | |
EditorGUI.PropertyField(position, property, label); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment