razorsese Posted December 23, 2014 Share Posted December 23, 2014 Is there any way to keep track like a pointer or something of a text?For example if I do something like this and try to destroy the text it only removes the last one created(i=19)for(var i=1;i<20;i++){ text = game.add.text(i*3+10,i*2+10,i style); text.anchor.setTo(0.5); text.font = 'Arial Black'; text.fontSize = 50; text.fontWeight = 'bold'; } Link to comment Share on other sites More sharing options...
XekeDeath Posted December 23, 2014 Share Posted December 23, 2014 Add it to an array...var textObjs = [];for(var i=1;i<20;i++){ text = game.add.text(i*3+10,i*2+10,i, style); text.anchor.setTo(0.5); /*These can be set in the style object passed to game.add.text... text.font = 'Arial Black'; text.fontSize = 50; text.fontWeight = 'bold'; */ textObjs.push(text);} Link to comment Share on other sites More sharing options...
lewster32 Posted December 23, 2014 Share Posted December 23, 2014 Just to elaborate on this, the reason only the last text object is being removed is because when you assign a variable or property, it will override anything it previously pointed to, as it can only point to a single object - so 'text' is set to the new object 19 times in your loop, before finally settling on the last one you set. Xeke quite rightly recommends you use an array for this, as an array allows you to store multiple values, add new ones to it with 'push' and then loop over them to access all the objects in the array. Here's a very verbose example just to demonstrate array usage:// Create an empty array and an empty stringvar myArray = [], myText = "";// Add the string 'hello' to the arraymyArray.push("Hello");// Add the string 'world' to the arraymyArray.push("world!");// Loop through the array. Each item of the array is given a number starting at 0, so// myArray[0] is the first item, myArray[1] is the second and so on. The array also has// a .length property so you can find out how many items are in the array - with that// info it's easy to create a loop...for (var i = 0, len = myArray.length; i < len; i++) { // ... and assemble a single string from the contents, putting a space after each word. myText += myArray[i] + " ";}console.log(myText);> "Hello world! "; Link to comment Share on other sites More sharing options...
Recommended Posts