Auto fills specific components fields

Hello again guys!

So, after reading through some feedback entries, I stumbled across this one:
https://feedback.unity3d.com/suggestions/automatically-inject-requirecomponent-fields

I thought that this was a wonderful idea, what it basically is auto fills component fills marked with the attribute RequireComponent, it not only adds (if there is not) the component in the gameobject, it also fills a specific field which was marked with that attribute. So I decided to implement this myself. Of course, the component must be serialized to work, this means that the component must be expanded and the inspector cannot be in debug mode, it also will not work with abstract class components like Collider, it must be a CapsuleCollider, BoxCollider, etc.

Here are the scripts:

This one 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 (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;

				Undo.RecordObject(mono.gameObject, "Add/Set Components to " + mono.gameObject.name);
			}
		}
		else
		{
			Debug.LogError("Field <b>" + fieldInfo.Name + "</b> of " + mono.GetType() + " is not a component!", mono);
		}
	}
}

And this one goes in any folder:

using UnityEngine;
public class RequiredComponentAttribute : PropertyAttribute
{
}

Yes, I like to keep attributes in a separate script, even if they are just a stub.

Thanks for reading, let me know if you can optimize it or add something to it.

Cheers,
Rodolfo Rubens

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s