Unity's RequireComponent
inherits from System.Attribute
. Somehow they made it that whenever component is added it has a reference to GameObject
its being added to. So they can call
AddComponent` to it.
I am trying to replicate that behaviour.
My theory is that because UnityEngine.RequireComponent
has types stored inside class - they do it by reflection later. In method AddComponent<T>
they get T
class attributes from type and then try to cast them, get information from them, and apply to GameObject
. If that is the case, then I doubt I will be able to do something with it, unless I have access to change AddComponent<T>
somehow.
Is there another way around it?(that is no problem to do in code (just extension), but what about how it will work in inspector) Maybe apply different method to Unity`s default component addition.
EDIT
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RequireComponentAttribute : Attribute
{
public RequireComponentAttribute(Type type, int quantity)
{
if (quantity < 0)
throw new ArgumentOutOfRangeException("Required components quantity cannot be negative");
}
#if UNITY_EDITOR
#endif
}
GameObject
or instance itself. The way to do it is by reflection I suppose. But anyway, for it to work in editor as expected, I would need to modify the internal code which doesn't work. The only way is probably to ask Unity to reveal API for it or make changes toRequireComponent
(that feature was requested a long time ago, but it doesn't seem important - it really isn't, just useful). \$\endgroup\$