JavaScript: mouse click on object

Hi there,
I am still new to GDevelop JS API and have some questions about it.
My goal is to react to a simple mouse click on an object.
I have a solution but is this best practice or did I miss some function?

var btn_restart = runtimeScene.getObjects("btn_restart")[0];

if(runtimeScene.getGame().getInputManager().isMouseButtonPressed(0) && runtimeScene.getOnceTriggers().triggerOnce() ) {
    console.log("Left Mouse Click")
    // Check if mouse is over button
    if(btn_restart.isCollidingWithPoint(runtimeScene.getGame().getInputManager().getMouseX(), runtimeScene.getGame().getInputManager().getMouseY())) {
        console.log("Button Restart clicked")
    }
}

That looks about right, though be careful, you need to pass in a trigger once identifier to the trigger once function. That is unlike events, where that identifier is autogenerated by the events code generator.

As for best practices, I’d say:

  • Don’t only use the first instance in the list, make sure you iterate on it to use them all
  • Basic javascript best practices, like using const/let instead of var.
  • Instead of getting a fresh instance list from the scene, reuse the one with picking from the events, by using the javascript events parameter to pass that objects list in.