Unity SiblingComponent Attribute
This file contains 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
namespace Core.Attributes | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using JetBrains.Annotations; | |
using UnityEngine; | |
[AttributeUsage(AttributeTargets.Field)] | |
[MeansImplicitUse] | |
public sealed class SiblingComponentAttribute : Attribute | |
{ | |
public bool Optional = false; | |
} | |
public static void AssignSiblingComponents(this Component component) | |
{ | |
IEnumerable<FieldInfo> fields = component.GetType() | |
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); | |
.Where(prop => Attribute.IsDefined(prop, typeof(SiblingComponentAttribute))); | |
foreach (FieldInfo field in fields) | |
{ | |
Type fieldType = field.FieldType; | |
Type componentType = fieldType.IsArray ? fieldType.GetElementType() : fieldType; | |
Component[] siblingComponents = component.GetComponents(componentType); | |
if (siblingComponents.Length > 0) | |
{ | |
field.SetValue(component, siblingComponents[0]); | |
} | |
else if (!field.GetAttribute<SiblingComponentAttribute>().Optional) | |
{ | |
Debug.LogError($"{component.gameObject} {component} - Unable to find sibling component of type {field.FieldType}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment