Hi everyone,
I’m building a shop UI where its contents are retrieved at runtime, so all UI elements (buttons, text, images) are instantiated and initialized dynamically.
Currently, I loop through an array of product data and instantiate one button per product. Each button has a script attached with an initialize() method, which receives product data and sets the button’s text and image accordingly.
The issue:
Visually, the text on each button appears to be one step behind:
The first button keeps its default text.
The second button displays the text meant for the first button.
The third button displays the text meant for the second button, and so on.
Interestingly:
The images are initialized correctly for all buttons.
When I click any button and log/print its stored data, the data is correct for that button.
For example, clicking the second button logs the second product’s data correctly - but visually, it shows the first product’s text.
I’m not sure I’m able to explain why this is the case at a technical level, but it is something I’ve adjacently run into before. Especially when dealing with text elements, you’ll want to make sure that it is fully ready to go before updating the text portion of the element. I was able to get the scene working as intended by changing your order of operations, and running your initialization function AFTER the element as been added as a child to the container:
...
if (this.shopItemButtonTemplate && this.shopItemButtonTemplate.resource) {
for (let i = 0; i < this._shopData.length; i++) {
const exchangeButton = this.shopItemButtonTemplate.resource.instantiate();
if (exchangeButton && exchangeButton.script) {
console.log(`Shop: Initializing exchange button ${i}...`);
this.buttonParent.addChild(exchangeButton); // This line aboveinitializeExchangeButton()
exchangeButton.script.button.initializeExchangeButton(this._shopData[i].longName, this._shopData[i].shortName, this._shopData[i].imageUrl, this._shopData[i].exchangeCost); // This line after child has been added
}
else {
console.error(`Shop: Failed to instantiate button ${i} with script!`);
}
}
}
...
Thank you so much! that worked perfectly. Your explanations are clear and I appreciate the code example
Will definitely keep this order of operations in mind for the future…