Hey folks,
There is no problem here, I’m just curious enough to want to ask a UI related question.
I understand that to have a button trigger a function within a script, that function needs to be public and the script itself attached to a gameobject which is then assigned to the OnClick event of the button.
Cool, that’s fine.
As someone who is at the start of learning Unity I’m just curious as to why a script cannot be assigned to the OnClick event of the button directly. Why the need to have it connected to a gameobject first?
Thanks!
Temmy
In unity, the normal flow of the program is done behind the scenes so you don’t have to do all of the usual setup work. Aside from that usual setup work, there isn’t much in code that you want to be “disconnected” from everything else. Why else would you want a function attached to a button unless it was going to interact with other objects from the scene?
Consider this: if you COULD put a random function on a button and that function was not tied to an object, what would you use it for? The only thing you could modify and have it truly matter in such a function would be static variables and data from your hard drive, which you can do just as easily from a function tied to an object.
This is the single biggest reason: Unity delegates. A delegate is like a unity function pointer, and can actually hold a list of functions as opposed to just one. A delegate must have an object and a function from a script on that object so when that delegate is “invoked”, it can have the object it’s pointing to call the function it was told to. “OnPress” is actually a delegate that is invoked when you press the button it’s on.