I am making a game in Phaser although I believe the core of this issue is a lack of my JS understanding.
I am looping through a Phaser container and wish to apply a click handler on each child sprite, but when I execute the click on any of the sprites, it always returns the last child.
I have tried various suggestions on Stack Overflow eg here: JavaScript closure inside loops – simple practical example
but can never get the click to return anything other than the last item.
An Example:
let items = //my container with 4 child sprites to click on
let i = 0;
item.list.forEach(function(obj) {
obj.setInteractive();
(function(i) {
obj.on('pointerdown', function(i){
console.log(i);
}.bind(this, i));
})(i);
i++;
});
In this example, every sprite I click on outputs ‘3’ tot he console, when it should output 0,1,2 or 3 depending on which was clicked.