Reset Method

The only real disadvantage of the Serialize Field approach is that you need to manually assign the Rigidbody reference every time you use the script, so this approach allows it to automatically find the Rigidbody while also retaining all of the advantages of the Serialize Field approach.

using UnityEngine;

public sealed class ResetMethodExample : MonoBehaviour
{
    [SerializeField] private Rigidbody _Rigidbody;

    private void Reset()
    {
        TryGetComponent(out _Rigidbody);
    }

    private void FixedUpdate()
    {
        _Rigidbody.AddForce(Vector3.up * 10);
    }
}

Unity calls the Reset method automatically when the component is first added (in Edit Mode only, not Play Mode) and also when you use the Reset function in the component's context menu.

Advantages

  • Most the same advantages of the Serialize Field Method, which are:
    • Fastest runtime performance - Unity deserializing the reference to set the field is faster than a script calling GetComponent on startup and the cost of calling it in Edit Mode doesn't actually matter.
    • The Inspector shows what other components the OnValidateMethodExample 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 same GameObject.
    • But the code is a bit longer (see Disadvantages).
  • It will automatically find the required Rigidbody (if there is one) when you first add the ResetMethodExample component.

Disadvantages

Summary Description Solution
Verbose This approach uses slightly more code than the Get Component Cached approach, making it one of the longest. The amount of code is still vary small so this isn't much of an issue, but most other approaches are a bit better in this regard.
Runs Once If you add or rename a serialized field after you have already added the ResetMethodExample to an object, the Reset method doesn't get called again so the new field will need to be assigned manually. The On Validate Method approach directly solves this problem.