Skip to content

Instantly share code, notes, and snippets.

@Vatyx
Last active April 12, 2024 12:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vatyx/36e7e85aec06ef9ac24622a68bd5d6b0 to your computer and use it in GitHub Desktop.
Save Vatyx/36e7e85aec06ef9ac24622a68bd5d6b0 to your computer and use it in GitHub Desktop.
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