[InitOnReset] attribute

  8. Reference No Comments

When a component that derives from MonoBehaviour<T> and has the InitOnResetAttribute is first attached to a GameObject in the editor, or when the user hits the Reset button in the Inspector’s context menu, the arguments accepted by the component are automatically gathered and passed to its Init function.

This auto-initialization behaviour only occurs in edit mode during the Reset event and is meant to make it more convenient to add components without needing to assign all UnityEngine.Object references manually through the inspector.

For example, when the following Player component gets added to a GameObject in edit mode, its Init method gets automatically called with Collider AnimatorController components from the same GameObject (if they exist):

[InitOnReset]
public class Player : MonoBehaviour<Collider, AnimatorController>
{
    [SerializeField]
    private Collider collider;

    [SerializeField]
    private AnimatorController animatorController;

    protected override void Init(Collider collider,
                                 AnimatorController animatorController)
    {
        this.collider = collider;
        this.animatorController = animatorController;
    }
}

By default component argument values are retrieved using the following logic:

  1. First the same GameObject is searched for a component of the required type.
  2. Second all child GameObjects are searched for a component of the required type.
  3. Third all parent GameObjects are searched for a component of the required type.
  4. Lastly all GameObjects in the same scene are searched for a component of the required type.

For each required component type the first match that is found using this search order is retrieved and then all the results are injected to the Init method.

It is also possible to manually specify which GameObjects should be searched for each argument. You can for example use the GetOrAddComponent value to try searching for the component in the same GameObject and then automatically adding it to it if no existing instance is found.

[InitOnReset(From.Children, From.GetOrAddComponent, From.Scene)]
public class Player : MonoBehaviour<Collider, AnimatorController, Camera>

Leave a Reply

Your email address will not be published. Required fields are marked *