Automatically assigning variables in Unity

When adding this component it will automatically assign the desired variables.

I found myself manually assigning the same variables over and over so I decided to see if I could automate that. In my application, which is for the HoloLens/Meta Quest, I use the MRTK buttons often and sometimes I need to change the text of the button or modify the toggled state if it's a toggle button.

My typical flow would be as follows:

  • Add the MRTK button to the hierarchy

  • Apply my custom button script

  • Manually assign each variable whether it be the TextMeshPro or the Interactable.

This became tiresome as I was building new pages for my UI. Here the script would need to inherit MonoBehaviour, as all Unity components do, to utilise the Reset() method. Here is the simplified code that I use:

public class CustomButton : MonoBehaviour
{
    [SerializeField] private TextMeshPro buttonText;

    private void Reset()
    {
        if (buttonText == null)
            buttonText = gameObject.GetComponentInChildren<TextMeshPro>();
    }
}

More info on the Reset() method can be found here. The main takeaway from the Unity docs is this:

Reset is called when the user hits the Reset button in the Inspector's context menu or when adding the component the first time. This function is only called in editor mode. Reset is most commonly used to give good default values in the Inspector.

Now all I have to do is add the MRTK button to the hierarchy and apply my custom button script. Hope this helps somebody!