Created
          November 30, 2018 18:00 
        
      - 
      
- 
        Save lawrence-laz/39903f3a5c7ace1652db19a2a6c01d29 to your computer and use it in GitHub Desktop. 
    Automatically get components in Unity using [GetComponent] attribute
  
        
  
    
      This file contains hidden or 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 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; | |
| } | |
| } | 
  
    
      This file contains hidden or 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 UnityEngine; | |
| [RequireComponent(typeof(Rigidbody))] | |
| public class Example : BaseBehaviour | |
| { | |
| [GetComponent] | |
| Rigidbody _body; // Example of auto GetComponent | |
| } | 
  
    
      This file contains hidden or 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
    
  
  
    
  | [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