Hey guys, I made a simple script that adds a useful functionality for component fields in inspector, instead of the “RequireComponent (typeof(CapsuleCollider))” attribute in the class I do this inside the class:
[RequiredComponent]
public CapsuleCollider col;
So, it will automatically get/add the required components to the col field when you add the monobehavior to an object, just like RequireComponent does but this also fills the field with the attribute.
Here is the code:
RequiredComponentDrawer.cs
Goes in an Editor folder.
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(RequiredComponentAttribute))]
public class RequiredComponentDrawer : PropertyDrawer
{
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.PropertyField(position, property);
MonoBehaviour mono = property.serializedObject.targetObject as MonoBehaviour;
//if(fieldInfo.FieldType.IsSubclassOf(typeof(Component)) )
if (typeof(Component).IsAssignableFrom(fieldInfo.FieldType))
{
if(property.objectReferenceValue == null)
{
Component comp = mono.GetComponent(fieldInfo.FieldType);
if(comp == null)
{
comp = mono.gameObject.AddComponent(fieldInfo.FieldType);
}
property.objectReferenceValue = comp;
//property.serializedObject.ApplyModifiedProperties(); // not sure if this is really needed
}
}
else
{
Debug.LogError("Field <b>" + fieldInfo.Name + "</b> of " + mono.GetType() + " is not a component!", mono);
}
}
}
RequiredComponentAttribute.cs
Goes outside the editor folder.
using UnityEngine;
public class RequiredComponentAttribute : PropertyAttribute
{
}
I hope this helps someone!
Forgot to mention, this was based on this feedback: https://feedback.unity3d.com/suggestions/automatically-inject-requirecomponent-fields