A different RequireComponent

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

6 Likes

You are awesome Rodolfo! that is exactly what I wanted in my feedback.

1 Like

For anyone else discovering this awesome thread and wishing that the above solution would work for non-public fields (I can’t shake the uncomfortable feeling of making fields public that don’t need to be), I have an alternative solution that requires inheriting from a base class.

Base class code:

using System.Reflection;
using UnityEngine;

public class BaseMonoBehavior : MonoBehaviour {

  protected void OnValidate() {
    foreach (var field in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) {
      var attributes = field.GetCustomAttributes(typeof(RequiredComponentAttribute), true);
      if (attributes.Length > 0) {
        Debug.Log(field.Name);
        System.Type fieldType = field.FieldType;
        Component component = gameObject.GetComponent(fieldType);
        if (component == null) {
          component = gameObject.AddComponent(field.FieldType);
        }
        field.SetValue(this, component);
      }
    }
  }

}

Property definition:

using UnityEngine;

public class RequiredComponentAttribute : PropertyAttribute { }

And finally, usage:

using UnityEngine;

public class Foo: BaseMonoBehavior {

  [RequiredComponent]
  private SpriteRenderer renderer;

  // Use this for initialization
  void Start() {
    renderer.color = Color.black;
  }
}

The OnValidate hook seemed like a good place for this.

2 Likes