One of the Disadvantages of the Get Component Cached approach is that when you look at it in the Inspector it gives no indication that it needs a Rigidbody
to actually work. So this approach simply adds a [RequireComponent
attribute to the class so that Unity will automatically add a Rigidbody
when you add the RequireComponentExample
component and won't allow that Rigidbody
to be removed first.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public sealed class RequireComponentExample : MonoBehaviour
{
private Rigidbody _Rigidbody;
private void Awake()
{
TryGetComponent(out _Rigidbody);
}
private void FixedUpdate()
{
_Rigidbody.AddForce(Vector3.up * 10);
}
}
Advantages
- Unity will automatically add a
Rigidbody
when you add theRequireComponentExample
component in the Inspector. - Same runtime performance as the Get Component Cached approach.
Disadvantages
Summary | Description | Solution |
---|---|---|
Verbose | The RequireComponent attribute makes the code quite a bit longer than the other approaches and means that the Rigidbody type is repeated twice. |
All other approaches are better in this regard. |
Inflexible | The RequireComponentExample needs to be on the same GameObject as the Rigidbody unless you edit the script. |
Serialized Field. |
Hidden Dependency | Looking at the RequireComponentExample in the Inspector gives no indication that it actually requires the Rigidbody unless you actually try to remove it. |
Serialized Field. |
Manual-Only | The [RequireComponent] attribute is enforced when you manually add the RequireComponentExample component using the Inspector, but not if you call gameObject.AddComponent<RequireComponentExample>(); . |
None of the other approaches really solve this one, but Serialized Fields make the requirements clear if you simply look at the Inspector. |