The most direct way to get a reference to another component is to use the GetComponent method.
using UnityEngine;
public sealed class GetComponentExample : MonoBehaviour
{
private void FixedUpdate()
{
var rigidbody = GetComponent<Rigidbody>();
rigidbody.AddForce(Vector3.up * 10);
}
}
The above example will search for a Rigidbody component attached to the same GameObject as this GetComponentExample component. Then it applies some upwards force to that Rigidbody.
Advantages
- Simple - When you need something, you just get it where other approaches require a bit more setup.
- Short - You could even write it on a single line as
GetComponent<Rigidbody>().AddForce(Vector3.up * 10);.
Disadvantages
| Summary | Description | Solution |
|---|---|---|
| Slow | Searching for another component has a notable performance cost which applies every frame with this approach. | Get Component Cached is the direct solution, but all other approaches solve this problem. |
| 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. |
| Becomes very verbose when repeated | If you need to access the Rigidbody in multiple places, repeating the GetComponent call for each one will take up a lot of space. |
All other approaches take a bit more code to set up a field, but then the field can be easily used throughout the whole script. |
| Inflexible | The GetComponentExample needs to be on the same GameObject as the Rigidbody unless you edit the script. |
Serialized Field. |