Using the script directly on the button

Greetings,

Would it be possible to add the script we create directly to the “On Click ()” section of the button instead of attaching it to a Game Object?

If it is possible but not recommended, why is that?

Thanks!

Hey rods012, it’s absolutely possible to add a script to the onclick via the AddListener method.

As far as doing it that way or the other depends on the context of what you’re trying to accomplish.

I am new to programming so I might be missing something, but it seems like the script on the page you linked to still uses a game object and is not directly attached to the OnClick of a button.

The situation in this case is in Number Wizard UI there are a few buttons that require us to attach a game object with a script that has the methods we need for the button to function as intended. I was wondering if there was a way to bypass the game object step of it.

Thanks for the quick response btw!

Yes the onClick is a Unity event, one way to subscribe to that event is by attaching a gameObject and giving it a method to call.

Another way is in code using the AddListener method

button.onClick.AddListener(methodToCall);

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms