Where the GetComponent
based approaches automatically find the Rigidbody
, this one exposes a field in the Inspector where you can manually assign it.
using UnityEngine;
public sealed class SerializeFieldExample : MonoBehaviour
{
[SerializeField] private Rigidbody _Rigidbody;
private void FixedUpdate()
{
_Rigidbody.AddForce(Vector3.up * 10);
}
}
This concept is known as Dependency Injection; ths SerializeFieldExample
class depends on a Rigidbody
, but instead of finding or creating one, it simply indicates that it wants one and relies on another system to assign it (in this case, Unity's serialization system).
Advantages
- Fastest runtime performance - Unity deserializing the reference to set the field is faster than a script calling
GetComponent
on startup. - The Inspector shows what other components the
SerializeFieldExample
depends on and which one is actually being used. - The other components can be anywhere. The script isn't hard-coded with the assumption that the
Rigidbody
will be attached to the sameGameObject
. - There's less code than the Get Component Cached and Require Component approaches, but a bit more than the original Get Component approach.
Disadvantages
Summary | Description | Solution |
---|---|---|
Manual | Each time you add this script to an object you need to drag and drop a Rigidbody into the Inspector field. |
Reset Method and OnValidate Method are the same thing with the ability to automatically try to find a reference. |