Glitch with Animation Completion and arrays

Hi everyone! I want to make a textbox that appears when certain conditions are met. When the condition is met, the textbox appears in a little animation and once the animation is over, it displays the text. Normally, this should work okay, but I have a problem when trying to display text based on an array. The first iteration works just fine, but after the first call “not with the battery” the game iterates through the command twice. For example, the first time, the game would display the text in array[0] like it should, but the next time it displays the text found in array[2], and the next time it’s called it will display the text in array[5]. Anyone know what the problem is? This doesn’t happen if I don’t play an animation.

Here’s the code in case if anyone needs to look at it. I apologize for the spaghetti code beforehand.

makeText(type){
this.textBox.text = “”;
this.mainText.text = “”;
this.textAnimation.setAlpha(1);
this.textAnimation.anims.play(‘textAnim’, true);
this.textAnimation.on(“animationcomplete”, () => {
this.textAnimationComplete = true;
if(type === “battery”){
this.textBox.text = “Battery Obtained!”;
this.mainText.text = “Your maximum battery has increased by 25!”;
}
else{
this.textBox.text = this.words.shift();
console.log(this.words);
this.mainText.text = “”;
}
});
}

Based on what you’ve described, my suspicion is that you’re duplicating your event listener. this.textAnimation.on("animationcomplete", ...) adds a new listener every time it’s called. If this.textAnimation stays the same between calls to makeText, you’ll add a new listener every time the method is called, which will start to duplicate the action - the code will run only once the first time you call it, then twice, then three times, and so on.

Try using this.textAnimation.once. The event listener will run once the animation completes and get discarded afterwards.

1 Like

Wow, I didn’t know the solution was that simple lol. Thank you, it works perfectly now!

1 Like