How can I add an eventListener to a button in a canvas?

Hi : ) I’m trying to trigger a characterMovement method when you click a button from the canvas, but I don’t understand how can I add a eventListener to that button in my script. Supose that I have a reference to the canvas (@serialiazable(GameObject) canvas:GameObject) and from this canvas I get the Button. Now, I want to add a eventListener to that button but I don’t get it yet.
I’m following the examples in the Intro to Needle Engine Scripting

Original Post on Discord

by user 632418299711324161

Hey :wave: the simplest way how to achieve that would be the unity way.

if you select your button in the editor, you should find the OnClick event in the inspector. There you add a entry with the + button.

There you need to drag & drop the GameObject with your script you want to be trigger and select the function in the dropdown.

—

Alternative flow is to reference the Button component and hook to the onClick event.

@serializeable(Button)
btn?: Button;

awake() {
  this.btn?.onClick?.addEventListener(() => console.log("Click"));
}

Hey! Thank uo : ) . For example, if I want to add a specific method called "GenericMethod’ in the alternative flow, How could I do that ?

by user 632418299711324161

there’s a small catch due to javascript binding

@serializeable(Button)
btn?: Button;

awake() {
  this.btn?.onClick?.addEventListener(this.handleClick.bind(this));
}

handleClick() {
  console.log("click");
}

Youre a hero Kipash, thank uo.

by user 632418299711324161

:smile: glad to help :cactus:

You can also use arrow functions to get rid of the manual binding:

awake() {
  this.btn?.onClick?.addEventListener(this.handleClick);
}

handleClick = () => {
  console.log("click", this);
}