AS3 MovieClip name ambiguity - actionscript-3

Summary: I create instances of various MovieClips via AS3, using MovieClip class objects that are defined in the library.
As each MC is instantiated, I push it into an array for later reference.
Finally I create an XML file that contains data related to each MC, including its name. This is the problematic part – the name has to be able to identify the respective MC when the XML is read back in. I don’t want “instance17” etc, which I assume will be meaningless in another session.
Background: I am not a career OO programmer and this is a temporary assignment, forming only a very small part of my long-term interests. It will probably be a couple of years before my next Flash project.
Create instance
Library object
Type: MovieClip, linkage _brakepipe
Instantiation
var brakepipe: _brakepipe = new _brakepipe();
shapes.push(brakepipe);
Then later
var clip: MovieClip = shapes(i);
Trace (clip);
This yields
[object _breakpipe]
So it is giving me the class name, not the MC instance name. What property or method of MC would yield “breakpipe”? (Or even "_breakpipe" - without the "object" prefix?)

You can use an associative array. It could look like this:
var shapes:Array = new Array();
and then
shapes.push({item:_brakepipe,_name:"brakepipe"};
Essentially the curly brackets create an Object instance and the name before the colon (:) is the name you create that you want associated with the value after the colon.
so now you can do this in a loop
trace(shapes[i]._name+"\n"+shapes[i].item);
// output:
// brakepipe
// [object _brakepipe]
The nice thing about this method is you can extend it for any number of properties you want to associate with your array element, like this:
shapes.push({item:_brakepipe,_name:"brakepipe",urlLink:"http://www.sierra.com",_status:"used",_flagged:"false"};
and now
shapes[i]._status
would return the string "used". And you could change that value at runtime to "new" by doing
shapes[i]._status = "new";

The Instantiation / Then later / This yields... Seems to be unclear for me, but you may try this and change the code...
Because I'm not sure not sure about the instance name you want to store...
In your loop you may do this if clip is a MovieClip! :
var clip: MovieClip = shapes(i);
clip.name = "breakpipe_" + i
trace (clip.name);
// will output : breakpipe_1 - > breakpipe_n...
You may deal with the clip.name later by removing the extra "_number" if you want.
If i == 13
var clip: MovieClip = new MovieClip();
clip.name = "breakpipe_" + 13
trace(clip.name);
// output breakpipe_13
var pattern:RegExp = /_\d*/g;
trace(clip.name.replace(pattern,""));
//output :
//breakpipe
So here, you may push your Array or Vector with the instance name.
Am I wrong?

Related

Objects within Objects

I have an object in my Library called Bottle. Bottle is made up of "Glass" and "Cap" instances. There are two more symbols in my library called Cap, and Glass.
When I click on the cap of Bottle, it says that this object is of class Cap, and when I click on the glass, it says it is of type Glass. Each one of these objects has base class flash.display.MovieClip.
However, in my code when I do:
var bottleOnStage:Bottle = new Bottle();
addChild(bottleOnStage);
var newColor:uint = 0x00ff00;
var newColorTransform:ColorTransform = new ColorTransform();
newColorTransform.color = newColor;
bottleOnStage.Glass.transform.colorTransform = newColorTransform;
I get this error:
TypeError: Error #1010: A term is undefined and has no properties. at MethodInfo-1()
Am I accessing the Glass property wrong? Is it because I haven't created an instance of Glass? I am confused on how objects within objects work in Flash.
EDIT
var cap:Cap;
var glass:Glass;
Above is what is in my Bottle.as file. In my Main.as file I have:
var bottleOnStage:Bottle = new Bottle();
bottleOnStage.cap = new Cap();
bottleOnStage.glass = new Glass();
addChild(bottleOnStage);
var newColor:uint = 0x00ff00;
var newColorTransform:ColorTransform = new ColorTransform();
newColorTransform.color = newColor;
bottleOnStage.glass.transform.colorTransform = newColorTransform;
When I run this code, no changes occur to the "glass" portion of the bottle. Why is this? I know that it is this line; I have traced and debugged all of the other lines, and the colors I am tracing are correct, etc. When I add "cap" and "bottle" to "bottleOnStage" using addChild, I get a duplicate of these two symbols, so this is apparently not the way. Basically, how do I modify "cap" and "glass" on stage?
It looks like your are confusing Classes with instances. Instance names cannot have the same name as a Class name (in the same scope).
Glass is your class. If you have variable with the name of "Glass" inside your bottle class, you need to rename it so it isn't ambiguous with your class name Glass.
bottleOnStage.glassInstanceName.transform.colorTransform = newColorTransform;
As a tip, to avoid this situation best practice is always make your instance names begin with a lower case letter, and always make your Class names begin with an upper case letter. (That also helps with code highlighting in most coding applications as well as here in Stack Overflow - notice how your uppercase items are hightlighted?)
As far as your error goes, you likely don't have an actual object in your variable yet.
Doing the following:
var myGlass:Glass;
Doesn't actually make an object (the value is null), it's just defining a placeholder for one. You need to instantiate using the new keyword in order to create an actual object.
var myGlass:Glass = new Glass();
Now you'll have an object in that variable.
EDIT
To address your edit, sounds like your probably want to something like this:
package {
public class Bottle extends Sprite {
public var cap:Cap;
public var glass:Glass;
//this is a constructor function (same name as the class), it gets run when you instantiate with the new keyword. so calling `new Bottle()` will run this method:
public function Bottle():void {
cap = new Cap();
glass = new Glass();
addChild(cap); //you want these to be children of this bottle, not Main
addChild(glass);
}
}
}
This keeps everything encapsulated and adds the cap and glass as children of the bottle. So bottle is a child of main, and cap and glass are children or bottle.
Whats is the name of the Glass attribute in the bottle?
if you have for example:
public class Bottle {
public var glass : Glass;
}
You can access the glass with:
var bottle : Bottle = new Bottle();
bottle.glass = new Glass();
Glass is the class. bottle.glass is the attribute "glass" of the class Bottle.
Hope it helps.

AS3 cloning an object

I've an object contain all types of data
var obj1:Object={boo:true,num:0,str:"me",arr:[0,"me2",[0,1]],mc:myMc,obj:{boo:false,num:0,str:"me3",arr:[0,"me4",[0,1]]}};
when I clone this object to obj2 using ByteArray with writeObject(obj1)& readObject()properties, everything is fine except obj2.mc (mc is a variable that hold the linkage of a movie clip in the library whose class is set to myMc) can not be added to stage,
addChild(new obj2.mc)
//TypeError: Error #1007: Instantiation attempted on a non-constructor.
Help please!!
You cannot duplicate movie clips that easy. It should be something similar to:
var objectClass:Class = Object(obj2.mc).constructor;
var instance:MovieClip = new objectClass() as MovieClip;
It would be much easier if you pass a Class rather than instance. In your case, that should be myMc - the class name of the object that is in the library, right?
If so, you can simply instantiate it directly: var instance:MovieClip = new myMc();
The important think to remember is that you don't need to hold reference to an instance, but the class instead!
Guys After 2 hours of experimenting, I came out with this, This is simply the perfect solution... I changed to another way than using ByteArray, which is writing each variable in obj2 to its corresponding value in obj1, but faced another problem: when I change arrays in obj2, I found that arrays in obj1 is changed too, this means when writing variables of obj2, arrays were only referenced to that of obj1.. so I had to loop through arrays to write each value in an array individually..
var obj1:Object={mc:myMc,bo:true,num:0,str:"me",arr:[myMc,true,0,"me2",[0,1,[0,1]]],obj:{mc:myMc,bo:false,num:0,str:"me3",arr:[myMc,true,0,"me4",[0,1]]}};
var obj2:Object=clone(obj1);
function clone( source:Object ):* {
var myOBJ:Object=new Object();
for (var property in source) {
if (source[property] is Array) {
myOBJ[property]=clone(source[property]);
} else {
myOBJ[property]=source[property];
}
}
return (myOBJ);
}
Thanks for all, you've inspired me..

AS3 Multiple instance names in one MC

I apologize for how confusing this question is.
I have a Movie Clip that is a car. In the car movie clip there are four different angles to the car. (e.g. left, right, front back). I dynamically change the body color of the car. In each angle of the car, the body of the car has an instance name "body." I change the color with the code :
var tempcar = "car_mc" + i;
var myNewTransform = new ColorTransform();
myNewTransform.color = 0x000000 //in real life this is a random value
this[tempcar].body.transform.colorTransform = myNewTransform;
Everything works fine, until I tell the car movie clip to gotoAndPlay the frame "front," where we see the front side of the car, and I try and apply the color change again to the body of the front of the car. I get the error :
TypeError: Error #1009: Cannot access a property or method of a null object reference.
Is there a better way to do what I am trying to do?
That's the old ActionScript 2 way of handling things. In ActionScript the container is not always a MovieClip, which would except the hash to access a dynamic field. Also, if you'd added it to the display list via addChild, the result would be different as well, since it is not the case in ActionScript 3, that could address the child automatically.
You should use an Array to store and access dynamically created instances.
// clazz would be the symbol
function createInstance(container:DisplayObjectContainer, clazz:Class, list:Array):Sprite
{
const child:MovieClip = new clazz() as MovieClip;
if (!child) throw new ArgumentError("Wrong type given");
return list[list.length] = container.addChild(child);
}
function getInstanceAt(index:int, list:Array):Sprite
{
return list[index] as Sprite;
}

I can't seem to access automatically named objects (instance##) placed on the stage in AS3, am I missing something?

I have a movieclip in the library that is added to the stage dynamically in the document class's actionscript. This movieclip contains many many child images that were imported directly from photoshop at their original positions (which must be preserved).
I do not want to manually name every single image instance, as there are dozens upon dozens.
I have already gone through and manually converted the images to symbols, as apparently flash won't recognize the "bitmap" objects as children of a parent movieclip in AS3 (numChildren doesn't see the bitmaps, but it sees the symbols).
I have an array filled with references to the dozens of children, and I loop through it, checking if each one is under the mouse when clicked. However, somehow, it is not detecting when I click over the items unless I manually name the child symbols (I tested by manually naming a few of them -- those ones became click-sensitive.)
I have already done trace() debugging all throughout the code, verifying that my array is full of data, that the data is, in fact, the names of the instances (automatically named, IE instance45, instance46, instance47, etc.), verifying that the function is running on click, verifying that the code works properly if I manually name the symbols.
Can any one see what's going wrong, or what aspect of flash I am failing to understand?
Here is the code:
//check each animal to see if it was clicked on
private function check_animal_hits():void
{
var i:int = 0;
var animal:Object = this.animal_container;
for (i=0; i<animal.mussels.length; i++)
{
if (this.instance_under_cursor(animal.mussels[i].name))
{
var animal_data = new Object();
animal_data.animal = "mussel";
this.send_data(animal_data);
}
}
}
Here is the code for the instance_under_cursor() method:
// Used for finding out if a certain instance is underneath the cursor the instance name is a string
private function instance_under_cursor(instance_name)
{
var i:Number;
var pt:Point = new Point(mouseX,mouseY);
var objects:Array = stage.getObjectsUnderPoint(pt);
var buttons:Array = new Array ;
var o:DisplayObject;
var myMovieClip:MovieClip;
// add items under mouseclick to an array
for (i = 0; i < objects.length; i++)
{
o = objects[i];
while (! o.parent is MovieClip)
{
o = o.parent;
}
myMovieClip = o.parent as MovieClip;
buttons.push(myMovieClip.name);
}
if (buttons.indexOf(instance_name) >= 0)
{
return true;
}
return false;
}
Update:
I believe I have narrowed it down to a problem with getObjectsUnderPoint() not detecting the objects unless they are named manually.
That is the most bizarre way to find objects under mouse pointer... There is a built-in function that does exactly that. But, that aside, you shouldn't probably rely on instance names as they are irrelevant / can be changed / kept solely for historical reasons. The code that makes use of this property is a subject to refactoring.
However, what you have observed might be this: when you put images on the scene in Flash CS, Flash will try to optimize it by reducing them all to a shape with a bitmap fill. Once you convert them to symbols, it won't be able to do it (as it assumes you want to use them later), but it will create Bitmpas instead - Bitmap is not an interactive object - i.e. it doesn't register mouse events - no point in adding it into what's returned from getObjectsUnderPoint(). Obviously, what you want to do, is to make them something interactive - like Sprite for example. Thus, your testing for parent being a MovieClip misses the point - as the parent needs not be MovieClip (could be Sprite or SimpleButton or Loader).
But, if you could explain what did you need the instance_under_cursor function for, there may be a better way to do what it was meant to do.

AS3 - Can't access properties or methods of a MC child that has been added in script

I am still a bit of a beginner at AS3, so bear with me, please.
I have created a loop to instantiate tiles on a board. In the following example, "Gametiles" is an array containing objects of class "Tile" which is a class that extends MovieClip. "Game" is a MC that I added to the stage in the flash developing environment.
for(var i:uint=0;i < Gametiles.length;i++){
var pulledTile = Gametiles[i];
var tilename:String = "I_Tile_" + pulledTile.grid_y + "_" + pulledTile.grid_x;
var createdTile = new InteractiveTile();
pulledTile.addAnims(createdTile);
Game.addChildAt(pulledTile, 0);
Game.getChildAt(0).name = tilename;
}
The above code works - but with a tricky problem. If I did something like the following:
trace(Game.I_Tile_1_3.x);
I get "TypeError: Error #1010: A term is undefined and has no properties."
However, I am able to access theses children in the following manner:
var testing = Game.getChildByName("I_Tile_1_3")
trace(testing.x);
This method is a bit cumbersome though. I really don't want to have to create a var and call getChildByName every time I want to interact with these properties or methods. How can I set up these children so that I can access them directly without the extra steps?
use the sqare brackets.
Trace(Game["I_tile_1_3"].x);