Last active
April 12, 2024 12:20
-
-
Save Vatyx/36e7e85aec06ef9ac24622a68bd5d6b0 to your computer and use it in GitHub Desktop.
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