addChild with looping, different name, and access variable - actionscript-3

here is my code
stop();
var card:mc;
for (var c:int = 1; c <= 2; c++){
card = new mc()
card.name = "card"+c
addChild(card);
this["card" + c].gotoAndStop(c);
trace(["card" + c].var1);
trace(["card" + c].var2);
}
in the movie clip i have two variable called var1 and var2 in the frame 1 and 2
but I get Error #1010: A term is undefined and has no properties.
at Untitled_fla::MainTimeline/frame1()

Display object name is not the same as field name inside the parent object. Normally you use getChildByName(name) and typecasting. In your code you don't need it as your object is already assigned to a local variable:
stop();
var card:mc;
for (var c:int = 1; c <= 2; c++){
card = new mc()
card.name = "card"+c
addChild(card);
card.gotoAndStop(c);
trace(card.var1);
trace(card.var2);
}

Related

problem accessing dynamic movieclips by name in adobe animate

I've done this a million time, but here it didn't work.
I have a game_mc inside a animate.fla. inside this clip I generate a view targetareas to place stones on it. ok, the TargetArea is a simple Movieclip inside my lib.
I can see everything, I can click on the area an get the propper name, I can get the names of the clips inside game_mc.
but I can't access it by using game_mc[clipname]
for (var i:int = 1; i<= 20; i++){
var targetArea:TargetArea = new TargetArea();
targetArea.txt.text = String(i);
var modu = ((i-1) %5);
targetArea.x = 100 + modu * 340;
var abs = int((i-1) / 5);
targetArea.name = "targetarea_" + String(i)+ "_mc";
targetArea.mouseChildren = false;
targetArea.y = 100 + (abs * 200) ;
game_mc.addChild(targetArea);
}
for(var x:int=0;x < game_mc.numChildren;x++) {
trace (game_mc.getChildAt(x).name);
}
for (var i:int = 1; i< 20; i++){
var targetName:String = "targetarea_" + i + "_mc"
trace( game_mc[targetName].x);
}
I think the name you assign your TargetArea instances isn't automatically converted
into a property of the DisplayObject you attach it to. As far as I remember though this
nonchalant way of accessing MovieClips using array access used to work prior to AS3.
The more elegant solution is to retrieve the child using getChildByName().
trace(game_mc.getChildByName(targetName).x);
Additionally, in case game_mc is an instance of MovieClip or a dynamic class you can make the TargetArea instances a property of it using:
game_mc[targetArea.name] = targetArea;
This way you can access them using game_mc[name].property afterwards.

Create sequential variable names under SharedObject in ActionScript 3.0

How to create multi variables in a SharedObject with ActionScript 3.0, using the same name except with sequential numbers 1-100 behind?
Besides dot notation you can access any object member with square brackets and the member name as a String variable. The following variants will equally invoke the play() method of the current MovieClip.
// Dot notation.
this.play();
// Square brackets.
var playName:String = "play";
this[playName]();
So it goes with any other object.
var SO:SharedObject = SharedObject.getLocal("my_shared_object");
for (var i:int = 1; i <= 100; i++)
{
SO.data["thing" + i] = Math.random();
}
UPD: As #Vesper pointed out, you can store a whole Array which lets you keep the indexed things naturally:
var SO:SharedObject = SharedObject.getLocal("my_shared_object");
SO.data.things = new Array;
for (var i:int = 1; i <= 100; i++)
{
SO.data.things[i] = Math.random();
}

Actionscript: get textfields and assign them dynamically

I'm trying to create a highscore list.
I have a movieclip ("highscore") and in it i have dynamic textfields with instance names. Now i'm trying to get those textfields so that i can change the text inside. Since i'm getting them in a loop i get them with getChildByName (and this works). But what i get back is a displayObject and therefore i get the error: implicit coercion of a value of type class to an unrelated type...
I know what the error is.. but i have no idea how to fix it.
Here is my code:
private function updateSingleList(result:XML):void
{
if(result['header']['success'] != 'true'){
return;
}
for(var i:uint = 0; i < result['items']['item'].length(); i++)
{
var pos:uint = i+1;
var name:String = 'name_' + pos;
var score:String = 'score_' + pos;
var rowName:TextField = highscore.getChildByName(name);
var rowScore:TextField = highscore.getChildByName(score);
rowName.text = result['items']['item'][i]['name'].toString();
rowScore.text = result['items']['item'][i]['score'].toString();
}
}
thanks!
Specify that the child you want is a TextField :
var rowName:TextField = highscore.getChildByName('name_' + pos) as TextField;
rowName.text = result['items']['item'][i]['name'].toString();

Displaying multipe Array-type attributes of sharedObject.data property in a single list

I have various food category pages (such as "Carbohyrates", "Meat", "Vegetables" etc) that have 3 comboboxes on each page where a user can select 3 different ingredients from each category (i.e. on the "Meat" page, a user can select 3 different types of meat). I write these 3 meats to a sharedObject as an Array like so:
Here is my saveMeat() function as an example so you can understand how I am forming my arrays:
function saveMeat(event:MouseEvent):void
{
_categoryMeat.btn_goback.removeEventListener(MouseEvent.CLICK, saveMeat);
removeChild(_categoryMeat);
if (meatDisableCheckBox.selected == true)
{
stop();
}
if (myComboBoxMeat.selectedLabel != null)
{
so.data.meat1 = myComboBoxMeat.selectedLabel;
trace(so.data.meat1);
}
if (myComboBoxMeat2.selectedLabel != null)
{
so.data.meat2 = myComboBoxMeat2.selectedLabel;
trace(so.data.meat2);
}
if (myComboBoxMeat3.selectedLabel != null)
{
so.data.meat3 = myComboBoxMeat3.selectedLabel;
trace(so.data.meat3);
}
var meat_items_array:Array = new Array(so.data.meat1, so.data.meat2, so.data.meat3);
so.data.meatItems = meat_items_array;
so.flush();
trace(so.data.meatItems);
}
There are several of these functions for each of the category pages (in all 6 different functions). They are all pretty similiar except for the fact the checkboxes and comboboxes differ.
I have a list function called dataLoaded that loads items from the sharedObject into the scrolling list:
private function dataLoaded():void
{
var i:Number;
for (i=0; i < so.data.meatItems.length; i++) {
_item = new Item();
// creates the var itemTextField //
_itemTextField = new TextField();
_itemTextField.text += '' + so.data.meatItems[i].toString();
//adds textfield to displaylist//
_item.addChild(_itemTextField);
}
}
As you can see, the for loop inputs the toString() representation of one of my attributes of my sharedObject (so.data.meatItems) into the TextField but I want to input all instances inside of my sharedObject no matter what sub-attribute they have. Also notice that I'm evaluating the length of the meatItems array in the for loop conditional, when I would want to be evaluating all items in the sharedObject
How can I do this?
EDIT: I implemented the below solution but am receiving this error:
TypeError: Error #1010: A term is undefined and has no properties.
at RecipeMatcher/dataLoaded()[/Users/adambull/Desktop/RecipeMatcherSO/RecipeMatcher.as:893]
at RecipeMatcher/displayList()[/Users/adambull/Desktop/RecipeMatcherSO/RecipeMatcher.as:212]
at RecipeMatcher/hideSplashScreen()[/Users/adambull/Desktop/RecipeMatcherSO/RecipeMatcher.as:192]
at Function/http://adobe.com/AS3/2006/builtin::apply()
at SetIntervalTimer/onTimer()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Here is my attempt at implementing the below (I have included my full function this time just in case there is something else in my function causing problems)
private function dataLoaded():void
{
// parsing of each ingredient//
// instantiation of mcItem (the stage for each item)
for (var item:* in so.data)
{
if (so.data[item] !=null)
{
if (so.data[item] is Array)
{
var a:Array = so.data[item];
for (var i:uint = 0 ; i < a.length;i++ )
{
_item = new Item();
// sets //over// layer to invisible / transparent //
_item.item_btn_over.alpha = 0;
// creates the var itemTextField //
_itemTextField = new TextField();
// _itemTextField visual attributes //
_itemTextField.x = _textFieldXPosition + _textFieldPaddingLeft;
_itemTextField.y = _textFieldYPosition;
_itemTextField.selectable = true;
_itemTextField.wordWrap = true;
itemTextField.width = _textFieldWidth;
_itemTextField.height = _textFieldHeight;
_itemTextField.embedFonts = true;
_defaultFormat.color = 0x111112;
_defaultFormat.font = _arialRounded.fontName;
_defaultFormat.size = 18;
_itemTextField.defaultTextFormat = _defaultFormat;
_itemTextField.appendText( so.data[item][i].toString() );
//adds textfield to displaylist//
_item.addChild(_itemTextField);
//vertical positioning//
_item.y = i * _itemPosition;
_item.btn_delete.visible = false;
_item.buttonMode = true;
_item.mouseChildren = false;
//adds items to container displaylist//
_container.addChild(_item);
}
}
}
}
// Input Mask//
_mask = new Shape();
_mask.graphics.beginFill(0xFF0000);
_mask.graphics.drawRect(0, 0, _maskWidth, _maskHeight);
_mask.graphics.endFill();
// Positioning of input mask//
// horizontal centering of input mask//
_mask.x = stage.stageWidth / 2 - _container.width / 2;
_mask.y = _paddingTop;
// adds the mask onto the stage//
addChild(_mask);
// assigns the above mask to the container //
_container.mask = _mask;
// Positioning of container with the mask//
// horizontal centering of container //
_container.x = stage.stageWidth / 2 - _container.width / 2;
// vertical position of container //
_container.y = _paddingTop;
//Container background stylings//
_background = new Shape();
_background.graphics.drawRect(0, 0, _container.width, _container.height);
_container.addChildAt(_background, 0);
//End of container background stylings//
_item.parent.addEventListener( MouseEvent.CLICK, itemClicked );
_container.addEventListener(MouseEvent.MOUSE_OVER, movingOver);
_container.addEventListener(MouseEvent.MOUSE_OUT, movingOut);
}
(I have tried adding an extra if to evaluate whether the content of each shared object attribute is empty or not - because I believe that if an array is empty this may cause another error?)
If I understood well you question, here is an example. It browse so.data, looks for arrays and then iterates on each one.
import flash.net.SharedObject;
var my_so = SharedObject.getLocal("superfoo");
// fill some fake values
var ar:Array = [1, 2, 3, 4, 5]
var ar2:Array = ['a1', 'a2', 'a3', 'a4']
my_so.data.array1 = ar;
my_so.data.array2 = ar2;
my_so.data.notarray = 'I m not an array';
my_so.flush();
// browse the so and find arrays
var my_so2 = SharedObject.getLocal("superfoo");
for (var item:* in my_so2.data) {
if (my_so2.data[item] is Array) {
var a:Array = my_so2.data[item];
for(var i:uint = 0 ; i<a.length;i++ ) {
trace('my_so2.data[' + item + '][' + i + ']=' + a[i])
}
}
}
Ouput (it skips items that are not Arrays in so.data)
my_so2.data[array2][0]=a1
my_so2.data[array2][1]=a2
my_so2.data[array2][2]=a3
my_so2.data[array2][3]=a4
my_so2.data[array1][0]=1
my_so2.data[array1][1]=2
my_so2.data[array1][2]=3
my_so2.data[array1][3]=4
my_so2.data[array1][4]=5

Why radioButtonGroup doesn't set its numRadioButons instantaneously?

Here is my code:
var x : int = 50;
var group : RadioButtonGroup = new RadioButtonGroup();
for (var i : int = 0; i < 5; i++) {
var rb : RadioButton = new RadioButton();
rb.id = i.toString();
rb.group = group;
rb.label = i.toString();
rb.x = x;
x += 40;
cnv_subContent.addElement(rb);//a BorderContainer
}
Alert.show(group.numRadioButtons.toString());
when i run the application, it shows me "0". Why this?
This is due to the flex component lifecycle. When a RadioButton is assigned a group, it doesn't actually get added until its commitProperties runs a frame later.
To get the correct group.numRadioButtons, you'll have to do things asynchronously. Something interesting is spark.components.RadioButtonGroup actually dispatches an undocumented "numRadioButtonsChanged" event whenever radio buttons are added or removed. It works but of course being undocumented use at your own risk.