Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unity SiblingComponent Attribute
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