Dynamically assign a class into an element in an array


,
Not sure if the title of this topic is correct, but what I'm trying to do is store a movieclip inside each array element using a for loop.
However, I have 2 movieclips to choose from and I want the movieclip to be randomly assigned to each element in the array.

Here's what I have so far but the syntax is obviously wrong:
Code: var enemyArray:Array = new Array(); var randomEnemyNo:int; var noOfEnemyMC:int = 2; for(var i = 0; i < 5; i++) { randomEnemyNo = (Math.floor(Math.random() * noOfEnemyMC) + 1); enemyArray[i] = new this["Enemy" + randomEnemyNo + "();"]; } OUTPUT:
Code: ReferenceError: Error #1069: Property Enemy1(); not found on RandomSpawn and there is no default value. ReferenceError: Error #1069: Property Enemy2(); not found on RandomSpawn and there is no default value. RandomSpawn is the name of my project.
I have an "Enemy1" and "Enemy2" movieclip in my Library.

.FLA and .AS attached as a .ZIP.

Can anyone help
Posted On: Thursday 3rd of January 2013 10:21:25 PM Total Views:  225
View Complete with Replies

RELATED TOPICS OF Flash / ActionScript PROGRAMMING LANGUAGE




Flash Reading XML attribues dynamically

Can anyine help with this problem, I'm new to flash and maybe I'm just missing the obvious. I have the following XML code: 60 65 69 74 78 83 64 70 75 80 84 89 etc........ and using the following lines I can trace the value. function SortCost(itemInput:XML):void { var itemBasePrice:XMLList = itemInput.height800.width800; trace (itemBasePrice); this returns the value 60. - O.K. The problem is that I need to create the XMLList variable dynamically through code so that I can select various heights and widths in string variables, then substitute them in the XMLList variable to extract the correct data. I know this doesn't work but code something like this: var ht:String = "height1"; var wd:String = "width800"; function SortCost(itemInput:XML):void { var itemBasePrice:XMLList = itemInput.ht.wd; trace (itemBasePrice);
VIEWS ON THIS POST

76

Posted on:

Thursday 25th October 2012
View Replies!

Loading multiple images dynamically

hi, trying to load several images to timeline keyframes, managed to load one, how to load several, Heres the code: var imageLoader:Loader; function loadImage(url:String):void { // Set properties on my Loader object imageLoader = new Loader(); imageLoader.load(new URLRequest(url)); imageLoader.contentLoaderInfo.addEventListener(Pro gressEvent.PROGRESS, imageLoading); imageLoader.contentLoaderInfo.addEventListener(Eve nt.COMPLETE, imageLoaded); } loadImage("Images/pori1.jpg"); function imageLoaded(e:Event):void { // Load Image imageArea.addChild(imageLoader); } function imageLoading(erogressEvent):void { // Use it to get current download progress // Hint: You could tie the values to a preloader }
VIEWS ON THIS POST

97

Posted on:

Thursday 25th October 2012
View Replies!

dynamically loading continuous scrolling background?

Hi. I was seen this effect on a few different sites, like the back ground on http://www.gap1969.com. It's like a continuous scrolling thumbnail list but in the x and y direction where the thumbs out side of the screen area aren't loaded until they are scrolled into the screen. Has anyone seen any tutorials on the best way to build something like this possibly an element matrix is being built and if the items are in the screen area they are then loaded
VIEWS ON THIS POST

106

Posted on:

Thursday 25th October 2012
View Replies!

assign keys to images

, I am trying to create a program where I assign movieclips in the library to a key. i.e, if I type in "cat", movieclips for "c", "a"and "t" would appear on the stage. Is there a way to do this
VIEWS ON THIS POST

78

Posted on:

Thursday 25th October 2012
View Replies!

Flash Question about Getting / Assigning values to a dynamically created button

Help me please.. I am currently working on a genealogy project. Problem : I want to assign a value to each of my dynamically created buttons but I can't get it right.. I created a for statement to loop on a record and create a button as my program walks past through them. Code: for (i= 0; i < xmlData.SomeCode.SomeCode.length(); i++) { var MemberInfo:String = xmlData.SomeCode.SomeCode.SomeCode[i]; var MemberIDStr:String = xmlData.SomeCode.SomeCode.SomeCode.SomeCode.SomeCode2[i]; var XStr:Number = xmlData.SomeCode.SomeCode.SomeCode.SomeCode.SomeCode3[i]; var YStr:Number = xmlData.SomeCode.SomeCode.SomeCode.SomeCode.SomeCode4[i]; var LEVELStr:Number = xmlData.SomeCode.SomeCode.SomeCode[i]; switch(LEVELStr) { case 0: LEVELStr = 0; break; case 1: LEVELStr = 40; break; case 2: LEVELStr = 80; break; case 3: LEVELStr = 120; break; case 4: LEVELStr = 160; break; case 5: LEVELStr = 200; break; } //THE FOLLOWING CODE BELOW CREATES BUTTONS ON EACH LOOP // USER() is a classified button out of stage. var newUserIcon:User = new User(); this.addChild(newUserIcon); newUserIcon.x = XStr+xOffset; ********** newUserIcon.value = MemberIDStr; newUserIcon.addEventListener(MouseEvent.MOUSE_UP,function(evt:MouseEvent):void {trace(newUserIcon.value);}); newUserIcon.y = LEVELStr+yOffset; //CREATE STATEMENT, ADD MORE OFFSET TO Y EVERY INCREMENT// } The add event listener must return a value as I click on it. I tried using the value method (refer to ******** line on the code), But it returns the latest MemberIDStr value. Is there a way to assign a unique value to every created button inside the loop Please help me, God bless.
VIEWS ON THIS POST

93

Posted on:

Thursday 25th October 2012
View Replies!

Placing elements into a dynamically created movieClip

I am trying to create a navigation element. The items in the navigation are created dynamically from data in an XML file. What I would like to do is create a new movie clip then place all of the navigation elements into that movie clip so I can move it around as one piece. Here is a simplified example of my code: Code: var navContainer:MovieClip = new MovieClip(); //clip to add elements to addChild(navContainer); //Create nav elements that I want inside navContainer// var reels:Array = []; function createReels():void { var reelPosX:Number = 336; for each (var titleElement:XML in titleList) { var reel:navReel = new navReel(); addChild(reel); reel.width = 119; reel.height = 119; reel.x = reelPosX; reel.y = 10; reels.push(reel); reelPosX+=155; } } I hope this makes sense.
VIEWS ON THIS POST

89

Posted on:

Thursday 25th October 2012
View Replies!

dynamically create class inside a class?

! This is what i'm trying to do : I have 1 class that extends movieclip, let's call it Class0. I have 1 class that extends movieclip, let's call it Class1. I create an instance of Class0 on stage like : var myClip0:Class0 = new Class0(this, "Class1"); The class Class0 when initializing, will create a new movieclip (myClip1) and add it as child, as an instance of Class1, like myClip0.myClip1. But it's when i create that clip, i want to tell it, it's an instance of Class1, like : private var myClip1:Class1 = new Class1(this); Where Class1 could be any class. How do i pass Class1 to Class0 so it can create it dynamically\t Do i have to use the apply function\t EDIT : inside Class0, i have a function that does : Code: if(subClass){ initSubclass(subClass); } private function initSubclass(type:Class):void { var subClass = new type(this); addChild(subClass); } } But that gives me the error : TypeError: Error #1034: Type Coercion failed: cannot convert subClass to Class And if i try : Code: private function initSubclass(type:String):void { var _class:Class = getDefinitionByName(type) as Class; I get ReferenceError: Error #1065: Variable subClass is not defined. But it works if i do a simple : Code: var test:subClass = new subClass(this); (where subClass here is the name of the Class)
VIEWS ON THIS POST

96

Posted on:

Thursday 25th October 2012
View Replies!

assign custom property

Hi i try to migrate from as2 to as3 and i have one problem When i attachMovie from library (addChild in as3) and i add custom property its work fine. Here is ex. Code: var i:int; for (i=0; i
VIEWS ON THIS POST

105

Posted on:

Thursday 25th October 2012
View Replies!

AS3: need help with dynamically adding multiple mc to one mask

hello, i'm trying to add movieclips to a single mask. but i cant seem to get it to work. is there a easy way to do this or do i have to remove the mask-child and add a new one again
VIEWS ON THIS POST

138

Posted on:

Thursday 25th October 2012
View Replies!

assigning URL to MCs via XML

So I'm trying to get better at AS3, and am working on a file that uses XML. I've got some of it to work, but can't wrap my head around this. My XML looks kinda like this: Code: portfolio/01.jpg one http://somelink.com/ with more than one "piece" obviously. I can get the XML and do stuff with the images (put them all on the stage with a for loop). Next I want to make the images link to the URLs, but I can't figure out how to assign the corresponding variable to the movieclips. I load the XML and run my for loop: Code: function xmlLoaded(e:Event):void { var loadedxml:XML = new XML(e.target.data); for (var i:uint=0; i
VIEWS ON THIS POST

61

Posted on:

Thursday 25th October 2012
View Replies!

AS3: use an mc to mask dynamically loaded images

I have created a custom 3d wall gallery and I would like to mask it to give it right and left fades. I have posted the code that places the images on the stage but for the life of me I cannot mask it. Themc in the library mask_mc already has the correct gradient so now how do I add it to the top of the dynamic gallery Any thoughts
VIEWS ON THIS POST

104

Posted on:

Thursday 25th October 2012
View Replies!

basic question - naming instances dynamically

My actual file is much more complex than this, but let's just say I need a loop that creates a bunch of xml files. Don't ask why, just try and accept that it's what I need... Something like: Code: for(i=1;i xml10. I've never learned how to create instances with names that are the combination of multiple existing strings/variable/whatever. It seems like it should be possible, but is it How
VIEWS ON THIS POST

85

Posted on:

Thursday 25th October 2012
View Replies!

functions assigned to escape key

I'm having a tough time getting the escape key to use a function. Every tutorial I go to it says that you need to import.flash.events.KeyboardEvent but when I use KeyBoardEvent in a function nothing happens. I get an error that says it couldn't load Why is this
VIEWS ON THIS POST

63

Posted on:

Thursday 25th October 2012
View Replies!

Can you assign one class to two moviclips in Library?

Hi all I need to assign one class to more than one movie clips created in Flash CS3. Is this possible\t
VIEWS ON THIS POST

62

Posted on:

Thursday 25th October 2012
View Replies!

HElp!! why I assign eventListener isn't working..

I draw a circleshape as Sprite and add it to stage ... Then addEventListener. not working.\t WHY WHY ================================================== ============= package { import flash.display.Sprite; import flash.display.MovieClip; import flash.display.Shape; import flash.events.MouseEvent; public class CircleShape extends Sprite { public function CircleShape() { var myCircle:Sprite = new Sprite(); myCircle.graphics.beginFill(0xFF, 1); myCircle.graphics.drawCircle(40, 40, 20); addChild(myCircle); myCircle.addEventListener(MouseEvent.CLICK, clickButton) myCircle.buttonMode = true; function clickButton ($evt:MouseEvent):Void { myCircle.alpha = .5; } } } } ===========================================
VIEWS ON THIS POST

52

Posted on:

Thursday 25th October 2012
View Replies!

How to dynamically create a Movie Clip ?

This one must be simple, I tried a few things but I'm not sure if the object I'm creating is a Movie Clip or not What exactly are Sprites and how can I create dynamically a movie clip
VIEWS ON THIS POST

53

Posted on:

Thursday 25th October 2012
View Replies!

why i have to import custom classes

Code: package { import flash.display.*; import example.test.Main; public class Document extends MovieClip { function Document() { new example.test.Main(); } } } it doesnt work without the 2nd import (import example.test.Main) why is it so
VIEWS ON THIS POST

66

Posted on:

Thursday 25th October 2012
View Replies!

more classes into one package or..

hi to all! i got flash cs3 some days ago, so i'm really new to actionscript 3. seems powerfull and i'm willing to dive into it. now, the first obstacle that i cannot pass (i googled it and searched in this forum) is: can i have more classes in one package if not, where can i put the file secondClassName.as and how to call it in order to be able to include it from baseClassName.as
VIEWS ON THIS POST

46

Posted on:

Thursday 25th October 2012
View Replies!

how to refer to the mc using this class

how do I refer to a mc that's using a certain class IN that class In AS2 I could use "this", but in AS3 I don't think it works
VIEWS ON THIS POST

58

Posted on:

Thursday 25th October 2012
View Replies!

Access mc inside dynamically attached mc? Please help!

I have an array of dynamically attached mc's, and I want to set text in a textfield that is inside movieclip that is inside each one of the attached mc's. I keep getting this error: TypeError: Error #1010: A term is undefined and has no properties. Here is the part of my code I'm having problems with. The mc is "square," the mc inside of it is "thumbText_mc," and the textfield inside of that is "hoverText": Code: function createThumbs(){ var myXML:XML=new XML(xmlLoader.data); for (var z:int = 0; z
VIEWS ON THIS POST

74

Posted on:

Thursday 25th October 2012
View Replies!

call a method outside its class

Hi! In AS2, i built my own EventDispatcher which was able to dispatch events in different classes. When I added an eventListener, the method needed 3 parameters: event, listenerObject, listener now AS3 got its own EventDispatcher, however, when you add an EventListener, it only requires two arguments: event and a function. But what do I do when I need to call a function that is placed in a other class Is there no way to call method of other classes with the EventDispatcher Class
VIEWS ON THIS POST

57

Posted on:

Thursday 25th October 2012
View Replies!

Reaching the documentclass

I have a document class, and it has been instanced and all is working fine. However, how do I "reach" it Is it called like "root" or something I would like to call it's functions.
VIEWS ON THIS POST

45

Posted on:

Thursday 25th October 2012
View Replies!

Tween class freezes a lot :-/

is there a bug, or am I doing most of my coding wrong i use a lot of Tweens and many of them freezes randomly without any particular reason
VIEWS ON THIS POST

60

Posted on:

Thursday 25th October 2012
View Replies!

Custom code hints for my classes?

If I have lots of AS classes that I want to use in a project, how can I set them up so I can get code hints the way I would with the native AS classes I would like to have code hints for public members and methods (along with argument names and data types for those methods). Also, is there supposed to be a more organized way of making large projects besides piles of classes and, in some cases, a library of movieclips, where each links to a class
VIEWS ON THIS POST

39

Posted on:

Thursday 25th October 2012
View Replies!

Adding a class constructor for my class gets TypeError..

I have a class Cannon, which is linked from my library.. When I don't have the constructor in, and on the first frame of my timeline I do: Code: addChild(new Cannon()); It works perfectly. But, when I add the constructor, even if there is nothing in the constructor, i get this error at compile-time: Code: TypeError: Error #1009: Cannot access a property or method of a null object reference. at Cannon$iinit() at cannon_fla::MainTimeline/cannon_fla::frame1() Does anyone know whats going on This is my shortened code with the constructor: Code: package { public class Cannon extends MovieClip{ ... public function Cannon(){ ... } ... } }
VIEWS ON THIS POST

71

Posted on:

Thursday 25th October 2012
View Replies!

When does one make classes?

I've coded in AS 2.0 for about one and half years, and migrating to AS 3.0 has been very difficult specifically because I never really dabbled in creating my own classes as my projects have very limited scopes. I understand that classes are great for reusability, encapsulation, and modularity. In spite of that, I'm still finding it hard to figure out when is a good scenario to use it.
VIEWS ON THIS POST

48

Posted on:

Thursday 25th October 2012
View Replies!

[AS3] making an auto-generated class inherit from custom class?

hi, just wondering if this is possible i was hoping to find a way to get a bunch of objects in my library to inherit from (or even be) one class that i have made, but without having to make .as files for every single one is this possible, or is there any other way to give objects another classes functionality in an auto-generated class cheers
VIEWS ON THIS POST

44

Posted on:

Thursday 25th October 2012
View Replies!

AS2.0: setInterval/setTimout kills class properties

I have this issue where I have a function that when it gets called via a setInterval (or setTimeout as I have tried both), it somehow makes my class vars undefined. I have traced it right before I call the timer, right after and then inside the following function that gets called. See below: Code: private function onRearTireSuccess (evt:Object):Void { allowRandomCars = true; _scoreboardTimer.reset(); _allowTorqueChange = false; setCarTimes(); dispatchEvent({type:ModelLocator.UPDATE_SCOREBOARD}); trace('onNewCar ' + currentCar); _nextCarTimeout = setInterval(onNewCar, _nextCarDelay); trace('onNewCar ' + currentCar); } private function onNewCar ():Void { trace('onNewCar ' + currentCar); clearInterval(_nextCarTimeout); if (this.currentCar
VIEWS ON THIS POST

72

Posted on:

Thursday 25th October 2012
View Replies!

30 minute progressive download FLV

Ok I have this 30 minute FLV that is progressively downloaded. The app also has chapter points that the user can click. This was orginally being built for use on a CD rom, but now they want it on the web things are changing..ughhh.. Anyway, my solution is to disabled all the chapter points until the FLV has loaded to that chapter point. How can I figure that out how much (in seconds) of the FLV has loaded
VIEWS ON THIS POST

69

Posted on:

Monday 29th October 2012
View Replies!

Platform game Error #1009

this is my first post so sorry if it is a bit confusing. I am creating a platform game and am getting the following error: #1009: Cannot access a property or method of a null object reference This error happens when I remove all children from the stage on line 154 of the Robbery.as class. Im guessing that maybe it is still listening for event in the other classes but I'm unsure how to remove these from within the document class. I have attached my game below. I hope someone can help
VIEWS ON THIS POST

37

Posted on:

Monday 29th October 2012
View Replies!

tlfMarkup ANYONE?

Well, so far I'm something like 0/4 in getting any help from this forum. I must be good at stumping . Latest issue: I have this project where text appears to write itself. I achieve this obviously through layer masks. What I've done is automate this through actionscript where instead of creating individual textboxes manually and tweening their masks, I create ONE textfield in a MovieClip. I can type a paragraph of text into this textfield and when the timeline reaches the clip, code is executed that does the following: breaks the paragraph of text into separate text containers that have the lines of text within them. Each of these textfields then has a mask that tweens itself when the preceding line of text's mask completes its tween. I hope that all makes sense. The problem is . . . what about local formatting ie, color and sub/super scripts. Originally I was using htmlText for color (worked great), but the sub/super script is a deal breaker. I've been trying to do this with tlfMarkup, but it puts the entire paragraph of text in each field instead of the individual lines. The good news is that it keeps the formatting. Any ideas I'll attach the code. You need to create a MovieClip with a textfield in it called "allText". On keyframe one, put the following code . . . init(whatever keyframe you place the movieclip on) You'll also need a movieclip in your library that's a plain rectangle, aligned to stage on the upper right hand corner. Export it as arrowMask(); (I have a controller skin for the movieclip with a scrub bar in the original project that the viewer can use to scrub back and forth through the animation . . . hence the remaining code at the bottom) package { import fl.text.*; import flash.display.MovieClip; import flash.text.TextFieldAutoSize; import fl.text.TLFTextField; import flash.text.TextFormat; import flashx.textLayout.elements.TextFlow; import flashx.textLayout.compose.IFlowComposer; import flashx.textLayout.elements.SpanElement; import flashx.textLayout.elements.ParagraphElement; import fl.transitions.Tween; import fl.transitions.easing.*; import flash.events.*; import flashx.textLayout.formats.*; public class blackbunnyTextBlue extends MovieClip { public var textString; public var X; public var Y; public var Lines; public var fmt:TextFormat = new TextFormat(); public var spaceBetween = 0; public var Arrow; public var hasFired = false; public var aMask = new arrowMask(); public var startFrame; public var totalPixels; public var endFrame; public var main ; public var Parent; public var masks = []; public function blackbunnyTextBlue() { } public function init(frameNumber):void { //only fire once unless scrubber is backed up if(hasFired == false) { Parent = MovieClip(parent); //format the existing field allText.autoSize = TextFieldAutoSize.LEFT; allText.wordWrap = true; allText.visible = false; //format new field var temp = new TLFTextField(); temp.htmlText = allText.text; temp.autoSize = TextFieldAutoSize.LEFT; temp.width = allText.width; temp.wordWrap = true; Lines = temp.numLines; textString = allText.text; X = allText.x; Y = allText.y; startFrame = frameNumber for(var i:int = 0; i < Lines; i++) { //for every line in the new text field, create a new single line field //with a line of text in it, a mask for it, and add them to the stage var lineText = allText.getLineText(i); var lineMetrics = allText.getLineMetrics(1); var Txt:TLFTextField = new TLFTextField(); Txt.border = false; Txt.wordWrap = true; Txt.htmlText = lineText; Txt.defaultTextFormat = fmt; Txt.autoSize = TextFieldAutoSize.LEFT; Txt.width = allText.width; Txt.x = X; Txt.y = Y ; Txt.embedFonts = true; Y = Y + (lineMetrics.height) + spaceBetween; addChild(Txt); var maskOne = new myMaskText(); maskOne.addEventListener(Event.ENTER_FRAME, engageInit); maskOne.x = Txt.x - 10; maskOne.y = Txt.y - 10; //mask init calculates what frame mask should move, end, and how far to move maskOne.init(i, startFrame); addChild(maskOne); masks.push(maskOne); //Set the mask to content Txt.mask = maskOne; } } hasFired = true; //listens for scrub bar backing up addEventListener(Event.ENTER_FRAME, checkFrame); } //only add the tween listener to the masks when their start frame has been passed by the scrubbar //this is trying to imitate the init code on a particular timeline public function engageInit(evt):void { if(Parent.currentFrame >= evt.target.startFrame && evt.target.hasFired == false) { evt.target.addEventListener(Event.ENTER_FRAME, tweenMe); evt.target.hasFired = true; } } public function tweenMe(evt):void { var masterFrame; masterFrame = Parent.currentFrame; var aMask = evt.target; //if the scrubber is between the start frame and end frame, tween the mask according to //the timeline's position if(masterFrame >= aMask.startFrame && masterFrame aMask.endFrame) { aMask.x = aMask.totalPixels; } //if the scrubber is dropped before the beginning frame, remove the event listener else if(masterFrame
VIEWS ON THIS POST

33

Posted on:

Sunday 30th December 2012
View Replies!