Skip to content

Instantly share code, notes, and snippets.

@lawrence-laz
Created November 30, 2018 18:00
Show Gist options
  • Save lawrence-laz/39903f3a5c7ace1652db19a2a6c01d29 to your computer and use it in GitHub Desktop.
Save lawrence-laz/39903f3a5c7ace1652db19a2a6c01d29 to your computer and use it in GitHub Desktop.
Automatically get components in Unity using [GetComponent] attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
public class BaseBehaviour : MonoBehaviour
{
protected virtual void OnEnable()
{
InjectGetComponent();
}
private void InjectGetComponent()
{
var fields = GetFieldsWithAttribute(typeof(GetComponentAttribute));
foreach (var field in fields)
{
var type = field.FieldType;
var component = GetComponent(type);
if (component == null)
{
Debug.LogWarning("GetComponent typeof(" + type.Name + ") in game object '" + gameObject.name + "' is null");
continue;
}
field.SetValue(this, component);
}
}
private IEnumerable<FieldInfo> GetFieldsWithAttribute(Type attributeType)
{
var fields = GetType()
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(field => field.GetCustomAttributes(attributeType, true).FirstOrDefault() != null);
return fields;
}
}
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Example : BaseBehaviour
{
[GetComponent]
Rigidbody _body; // Example of auto GetComponent
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
class GetComponentAttribute : System.Attribute
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment