Skip to main content
TheOriginalGC
Community Expert
Community Expert
Jun 24, 2022 2:13 PM UTC
Answered

Add symbol to stage in JS and push to array

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();

This topic is closed to new replies. Start a new post to keep the conversation going.
JoãoCésar17023019
JoãoCésar17023019Correct answer
Community Expert
Jun 24, 2022 5:09 PM UTC

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

5 replies

JoãoCésar17023019
Community Expert
JoãoCésar17023019Community ExpertCorrect answer
Community Expert
Jun 24, 2022 5:09 PM UTC

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

Translate
TheOriginalGC
Community Expert
Community Expert
Jun 24, 2022 5:19 PM UTC

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).

Translate
JoãoCésar17023019
Community Expert
Community Expert
Jun 24, 2022 5:24 PM UTC

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.

Translate