Copy link to clipboard
Copied
Trying to dynamically add symbols from library to an array using JS. Using the code snippet to add one instance, but multiple instances causes problems with the array. Here's my code:
var newCoin = new lib.Coin();
function loadCoins(){
for(let i = 0; i < 6; i++){
myCoins.push(newCoin);
root.addChild(myCoins[i]);
}
}
loadCoins();
Hi.
Please try this:
var root = this;
var myCoins = [];
function loadCoins()
{
var newCoin;
for(let i = 0; i < 6; i++)
{
newCoin = new lib.Coin();
myCoins.push(newCoin);
root.addChild(newCoin);
}
}
loadCoins();
Regards,
JC
Copy link to clipboard
Copied
Hi.
Please try this:
var root = this;
var myCoins = [];
function loadCoins()
{
var newCoin;
for(let i = 0; i < 6; i++)
{
newCoin = new lib.Coin();
myCoins.push(newCoin);
root.addChild(newCoin);
}
}
loadCoins();
Regards,
JC
Copy link to clipboard
Copied
Thank you, that did the trick. I was convinced that I couldn't have the newCoin object in my function without declaring it first. Also, I needed to have an instance of the symbol already on the stage for the thing to work. (It turns out that if it isn't on the stage, it doesn't get added to the sprite atlas, making the rest of the code hard to run).
Copy link to clipboard
Copied
The big catch here is that you must call new lib.Coin() in the for loop. If you call it outside the loop, you're gonna create only one instance and add it six times to the array.
Copy link to clipboard
Copied
Which is exactly what I was doing. Thanks again.
Copy link to clipboard
Copied
You're welcome!
Find more inspiration, events, and resources on the new Adobe Community
Explore Now