One of the Disadvantages of the Get Component approach is that it has poor performance because it searches for the component every frame, so the obvious way to avoid that issue is to search only once on startup and store a reference to the other component so you can use it without searching again.
using UnityEngine;
public sealed class GetComponentCachedExample : MonoBehaviour
{
private Rigidbody _Rigidbody;
private void Awake()
{
_Rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
_Rigidbody.AddForce(Vector3.up * 10);
}
}
Needing to specify the Rigidbody
type for both the field and the GetComponent
call is not ideal, and fortunately it can be easily avoided by using TryGetComponent
instead:
// Replace this:
_Rigidbody = GetComponent<Rigidbody>();
// With this:
TryGetComponent(out _Rigidbody);
// Because the compiler already knows the type of '_Rigidbody' so you don't need to do:
TryGetComponent<Rigidbody>(out _Rigidbody);
This allows the code to be a bit shorter, but more importantly it also means that if you decide to change the field's type to something else (such as a CharacterController
), you only have to modify the field and the TryGetComponent
will automatically infer the new type. This reduces the number of other things you need to fix when changing this part of your code, which is good for productivity.
Advantages
- Better performance than the Get Component approach.
Disadvantages
Summary | Description | Solution |
---|---|---|
Unsafe | Adding the GetComponentExample component to an object in the Unity Editor gives no indication that it also needs a Rigidbody component attached to the same object. You will only find out when you try to run the game and it spams the Console window with a MissingComponentException every frame. |
Require Component helps, but Serialized Field is better. |
Inflexible | The GetComponentExample needs to be on the same GameObject as the Rigidbody unless you edit the script. |
Serialized Field. |