AS3: Change TextField Text on multiple instances of the same MovieClip - actionscript-3

I have a MovieClip called "number" in the library. I need to add multiple instances of that MovieClip to stage. Instances should be called number1, number2,number3...and each one needs to have different text inside it.
Is it possible to do this without code, just using flash interface tools? If not, could someone help me with coding that?
Thanks!

For an Class linked MyNumber containing a text field named output:
const N:int = 3; // 3 instances
const TEXTS:Array = ['text 1', 'text 2', 'text 3']; // 3 texts
var n:MyNumber;
for (var i:int = 0; i < N; i++) {
n = new MyNumber();
n.y = 50 * i;
n.output.text = TEXTS[i];
this.addChild(n);
}

You have to use code - at least a little bit.
In addition to #helloflash's answer, here is a simpler solution (with some caveats described below).
On your movieClip, make your text box dynamic, and give it an instance name of txt (or whatever you'd like). Then, put the following line of code on the first frame of your movieClips's timeline:
txt.text = this.name; //works if your text is a simple word with no spaces/puntuaction/symbols and doesn't match any actionscript keywords
This will set the text to whatever the instance name of each movieClip is. Will work great if you text is something simple like "Hello" or "Player1".
Now, if you're text is a number (or starts with one), or your text matches a keyword or already defined variable (like this/continue/function/break/stop/play etc), you'll need make it a bit more complicated, something like this:
txt.text = this.name.replace("$MC_","");
Then give your instance name in this format: $MC_stop, the code will strip out the $MC_ part and show the rest. so the text field would be "stop".
Now, if you want to include spaces, or most symbols (dollar sign, underscore and dash I think are the only supported ones), you'll have to add a replace for each one and create a place holder for that character.
So if your text was "This is my text", you should give it an instance name of `this_is_my_text" and this should be the code:
txt.text = this.name.replace("_"," "); //replace all underscores with space
Add as many replace statements for as many characters you need.
So, if you text was "1. This is my text!!!" - The instance name could be: $MC_1$dot_This_is_my_text$ex$ex$ex and the code:
txt.text = this.name.replace("$MC_","").replace("_"," ").replace("$dot",".").replace("$ex","!"); //you can keep chaining on as many replace statements as you need.
Of course, at this point you might as well just use full on code like #helloflash's answer. But if you text isn't that complicated, this may be a good solution for you.

Related

Square bracket notation to dynamically load library items?

So I've spent an embarrassing number of hours trying to save myself a few minutes and make my code a bit neater, and Google has produced nothing, so now I come crawling to stackoverflow. The problem is with square bracket notation + library items:
So let's say you have a MovieClip called "myMC_5", and you want to set its X position to 0..
myMC_5.x = 0;
..and if you don't want to hard-code the name of the MC but instead you want one line of code to move a specific MovieClip based on a variable, you could do something like this:
var selectMC = 5;
root["myMC_"+selectMC]x = 0;
..and this will have the exact same effect as myMC_5.x = 0, except that this time you must specify the location ("root" or "this" or something).
THE PROBLEM:
I'm working on a game in which the graphic for the background is loaded from the library, and it's different for each level. The initial loading of the vector from the library looks like this:
private var land:vector_land0 = new vector_land0();
..and this works fine, but it only loads that one specific vector. There should be about 30 or more. I'd like to just have 1 line of code in the constructor to load any of them, based on a variable which keeps track of the current level, like this:
private var land:["vector_land"+theLevel] = new ["vector_land"+theLevel]();
..but that doesn't work. I get syntax errors ("expecting identifier before leftbracket") because you need to specify the location of the object, like in the first example:
root["myMC_"+"whatever"].x = 0;
..but this library item has no "location". So, how the heck do I dynamically load a vector from the library? It's not "on the root", or anywhere else. It has no location. I refuse to believe that the standard method for accomplishing this is to create 30 different classes or write a giant block of code with 30 "if" statements, but searching Google has found nothing. :(
It sounds like you're looking for getDefinitionByName(), which you could use to do something like this:
import flash.utils.getDefinitionByName;
private var LevelVectorClass:Class = getDefinitionByName("vector_land" + theLevel) as Class;
private var land:Object = new LevelVectorClass();
This is a horrible way to solve the situation, I don't recommend using square brackets anywhere but arrays. I recommend you putting the "lands" into a LandContainer MovieClip, each frame of that MovieClip would container 1 graphic. It is much cleaner, and you could create constants to store the "identity" of the frames.Example:
var land:LandContainer = new LandContainer();
land.gotoAndStop(FIRST_LEVEL); //FIRST_LEVEL is a constant integer
You can even reuse this LandContainer instance because you can set it's visibility, remove from the display list, set it's frame to the next level without creating another instance. On second thought, I would write a wrapper for this class. Aka link it to your own class which extends the MovieClip class and create custom functions, fields... etc..
This dynamic thing is horrible, hard to maintain, and not efficient at all. Don't know why did not they delete it from AS3... they should have.

as3 remove white space

I am trying to remove / replace white space from a string in as3. The string comes from xml and than written into text field. to compare the strings I am trying to remove white spaces
var xmlSentence:String=myXML.SENTENCE[thisSentence];
var tfSentence=e.target.text;
var rex:RegExp = /\s+/;
trace(xmlSentence.replace(rex, "-"));
trace(tfSentence.replace(rex, "-"));
That code outputs like this:
She-has a dog
-She has a dog
I also tried different rex patterns. the problem is that though there are spaces in both string -which are same- it finds only one space but not the same one in both strings.
Could you help me to solve this problem
Thanks in advance
You need to use the g flag to indicate recursive changes
var rex:RegExp = /\s+/g ;
Within your Actionscript code, select the RegExp keyword, then goto the 'Help' menu and choose 'Flash Help' for more info on flags.

retrieving a variable value from lower level

well i created some variables in the main stage level, with something like this:
for(i=0,i<10,i++){
var var_name="var_num_"+i;
this[var_name]="some value";
}//<-----------------------------------------------------works
so i get 10 variables named "var_num0", "var_num1", "var_num2" each one with some value.
and i can acces them any where calling this
var second_var=MovieClip(root).var_num0;//<--------------works
my problem comes when i want to call all the variables from a lower level or in another frame or somewhere else using another loop:
var third_var;
for(j=0,j<3,j++){
third_var=this["MovieClip(root).var_num_"+j];//<---------DOSNT WORK
trace(this["MovieClip(root).var_num_"+j]);//<------------returns "undefined"
}
how can i make this work? i tried a lot of things and nothing...
thanks you all
In your case both "root" and "this" are the scope you want to access the vars from. so try this:
var third_var:MovieClip;
for(j = 0; j < 3; j++)
{
third_var = MovieClip(root)[var_num_ + j];
trace(third_var);
}
Also you should have semi-colons in your for loop rather than comers.
I'd like to preface my answer with a suggestion you use a 'Document Class' with AS3 to make things like namespaces and inheritance much clearer. You know exactly where things are accessible when using document based, object oriented programming versus the timeline programming available through the Flash IDE (its only there because of AS1/2). Tut: http://www.kirupa.com/forum/showthread.php?223798-ActionScript-3-Tip-of-the-Day/page14
On to the answer: You are trying to move two levels of inheritance in one set of [] Another way of writing your first "Doesn't work" line is:
this.myMovieClip["var_num"+j"];
You could also use: this["MovieClip"]["var_num"+j];
Basically, you need to take the "MovieClip(root)" out of the string you are using to call your variable because you are passing through two levels of inheritance: this->MovieClip->targetVar
You need to use two periods, a period and a set square bracket or two sets square brackets to move two levels of inheritance. A period . and a set of square brackets [] both accomplish the task of moving one level deeper, so putting the . inside the string used to call up your variable won't work.
Explanation:
The following three examples all return the same variable:
myMovieClip.my_variable
myMovieClip["my_variable"]
var str:String = "my_variable";
myMovieClip[str];

Read Text File with AS3 and Tween Each Word from Small to Large out of the screen

I am looking for some advice on the best way to read in like 200k words and have them each tween from the center of the screen as small dots and tween up to the word filling the SWF then "fly through my head" not literally, but you probably get it...
What would be the best way in AS3 to go about this? I am fairly new to it.
Thanks!
Depending on the origin of your text, you may have to use regular expressions to get rid of punctuation and replace any amount of spaces by a set delimiter.
You could then use the split method of the String class to turn your text into an Array of words.
Each word can then be assigned to a Textfield. Since the Textfield is a DisplayObject, all the manipulations you are mentioning above become possible.
You may be able to streamline all this by creating a class that extends Textfield and defining various methods for the motions you want to implement.
You'll probably want to look at the Timer class and some tweening libraries
Pseudo Code
- Clean up String with regular expressions
-> expected result var cleanString:String = "word1;word2;...wordn";
- Turn String into Array
var words:Array = cleanString.split( ";" );
- Create a class that extends Textfield and define a manipulate() method
var tf:MyTextField = new MyTextField();
//this method could take parameters
//such as x, y, scale , time , delay , ease etc...
tf.manipulate();
- Create an Array( Vector ) of Textfields
loop thru words Array to return array of Textfields
var objects:Array = [ tf1, tf2 , etc...]
- Manipulate objects
loop thru objects Array to manipulate them
if you don't want to do it by hand (like PatrickS described) maybe this will help you ...
http://www.greensock.com/splittextfield/

Actionscript 2.0 and 3.0: Specific "text" in input box causes certain image to display

I want to know how(and what scripts) to take words from a text input box and cause it to display and image Ex: if the text box said "smiley face" in it, then the image "smiley_face.jpg" would display on a certain movieclip and can be dragged around the stage and when a new image is loaded, it doesn't replace the previous image on the movie clip.
You need to listen for the textInput event and you need to constantly search for "smile" using something like the search() function(u can use strings or regular expressions).
It returns -1 if the string you're searching for wasn't found, otherwise it returns the first index where the searched string was found.
Here's a really basic example:
var ti:TextField = new TextField();
ti.type = TextFieldType.INPUT;
ti.border = true;
addChild(ti);
ti.addEventListener(TextEvent.TEXT_INPUT, onInput);
function onInput(event:TextEvent):void {
if(ti.text.search('smile')!=-1) trace('display smiley image');
}
You did mention smileys, so depending on your level of comfort with actionscript 3, it might be also worth having a look at Thibault Imbert's SmileyRenderer. Careful it uses the new FTE so you need to use Flash Player 10, etc.
yeah. In ActionScript you need to add a listener event to the text field. then you can do something like this. My action script is not so good so I will just stick with logic.
if listener.text == "smile"
smile.jpg
else if listener.text == "frown"
frown.jpg
else
default.jpg
end
You should check out lynda.com for their basic AS screencasts