Skip to main content
TheOriginalGC
Community Expert
Community Expert
June 24, 2022
Answered

Add symbol to stage in JS and push to array

  • June 24, 2022
  • 1 reply
  • 380 views

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 has been closed for replies.
Correct answer JoãoCésar17023019

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

1 reply

JoãoCésar17023019
Community Expert
JoãoCésar17023019Community ExpertCorrect answer
Community Expert
June 24, 2022

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

TheOriginalGC
Community Expert
Community Expert
June 24, 2022

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

JoãoCésar17023019
Community Expert
Community Expert
June 24, 2022

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.