Calling the onPress function, programmatically, from a different script

Editor:

Code:

Launch:

I’m working on ETA’s token spawner (the button in the bottom-left corner), and I’ve run into a problem. When the user clicks on a button, that button becomes selected. If another button is then selected, the first should become un-selected. I have written script that should de-select any other buttons that are selected by calling the onPress function of the relevant scripts (cyan/gold/green/magentaButton.js, lines 47 - 60). However, this causes a number of problems. The problem reported by PlayCanvas is a TypeError:


An example of the relevant scripts:


The commented script just below the onPress() function is a copy-paste of a similar script: ruler.js

The strange thing is, this error only appears when trying to select multiple token buttons. When using ideal input (de-selecting a button manually before selecting another), this TypeError is never thrown. Any idea why calling the onPress() function without actually clicking the relevant entity would throw such an error?

The onPress function is expecting an event object to be passed to it but when you call pragmatically, you don’t pass any parameters hence event is undefined.

A couple of ways to fix this:

  • don’t use event in the onPress function as it looks like you don’t need it for the current logic
  • create separate functions to select and deselect the button
  • create an event object to pass when calling the onPress function

I personally prefer option 2. onPress is an input callback and practice wise, shouldn’t be called programmatically.

1 Like