Reputation: 67
In Flash, I created a grid of 400 buttons with instance names c0
through c399
.
In Actionscript, I'd like to create an array like this:
var myArray:Array = [c0,c1,c2,c3,c4,c5,c6];
all the way up to c399
.
I wrote a for-loop to do the trick, but it doesn't seem to be working:
import flash.events.MouseEvent;
//create the array
var myArray:Array = [];
for (var i:int=0;i<399;i++){
var cletter:String = 'c';
var p:String = i.toString();
var newvalue:String = cletter + p;
var shizzle:Object = new SimpleButton();
myArray[i] = shizzle;
}
for each(var btn in myArray){
btn.addEventListener(MouseEvent.CLICK, onBtnClick);
}
function onBtnClick(event:MouseEvent):void{
cellinfo.gotoAndStop(event.target.name);
}
When I publish it, no errors show up and nothing happens when I click the buttons. However, if I use
var myArray:Array = [c0,c1,c2,c3,c4,c5,c6];
it does work! (for the first 7 buttons at least).
Also, when I put:
for (var i:int=1;i<6;i++){
var cletter:String = 'c';
var p:String = i.toString();
var newvalue:Object = cletter + p;
myArray[i] = newvalue;
}
it says:
TypeError: Error #1006: value is not a function. at PVproject1_fla::MainTimeline/frame1()
I just started working with AS3 + Flash and spent hours looking for a solution. Please help!
Upvotes: 0
Views: 3136
Reputation: 6961
Another solution is to just watch for them to be added to the stage and capture them at that point, similar to one of the examples you can download here http://flexdiary.blogspot.com/2010/04/sample-code-for-oop-timeline-insideria.html
Upvotes: 0
Reputation: 22604
Your code is broken in more than one way.
for (var i:int=0;i<399;i++){
var cletter:String = 'c';
var p:String = i.toString();
var newvalue:String = cletter + p; // => this is never used
var shizzle:Object = new SimpleButton(); // => this creates a new (!) button
myArray[i] = shizzle;
}
Each of the 400 newly created buttons is never added to the stage, therefore you can't see it. And since it has no skin or other visual properties, you wouldn't be able to see it if it were.
The second for-loop puts only the names into the array - which causes the "value is not a function" error when you try to access the array values as buttons, because the value is really a string:
for (var i:int=1;i<6;i++){
var cletter:String = 'c';
var p:String = i.toString();
var newvalue:Object = cletter + p; // <= this is a String!
myArray[i] = newvalue;
}
Now apart from a fundamental doubt whether you'd really want to create 400 button instances by hand (I'd think about doing it in ActionScript and using this actual creation to fill the array), you can do the following - but remember: only if the button instances are already on the stage, and the loop is located in a frame script!
for (var i:int=0;i<399;i++){
myArray[i] = this["c"+i]; // no need for all the p and .toString() stuff, btw
}
Upvotes: 1