0

enter image description here

Unity has a component called Button as part of its UI system which you can use to subscribe on-click events to it through the inspector which is incredibly useful.

However, when projects get larger, I run into trouble in many situations:

  • events subscribed this way in the inspector are not rearrange-able which makes buttons that have lots of events difficult to manage
  • changing the contents of the scripts used for events can cause the button to not recognize a function that was used for an event which means you have to re-reference it
  • if anything happens to the GameObject or prefab that stores the Button component such as it getting corrupt then all your events that were serialized onto the button would be wiped and you would need to re-reference all of them
  • the above points make debugging very very difficult

What are some ways I can work around the problems I've listed above?

  • 1
    Unfortunately this is just a point of friction in Unity development, theres a tradeoff when deciding whether to do something through the inspector or in code. Because of the reasons you mentioned, I would instead have a UI Controller script which has references to the buttons, and then assigns OnClick handlers in the script. – Josh Bothun May 11 '22 at 12:59
  • Well the answer would probably be: completely separate the UI from the logic and do as much in code as possible .. this way anything Unity specific like serialization and references etc won't matter – derHugo May 11 '22 at 14:25

1 Answers1

1

Inject event functions inside the code:

public Button playButton; // set button in inspector

public void Start()
{
    playButton.onClick.AddListener(() =>
    {
        transform.position = point1;
        
        // do something..
    });
}
KiynL
  • 4,097
  • 2
  • 16
  • 34