ActionScript 3 - How to target textbox inside movieclip - actionscript-3

I have a movie clip called radio and flashlight. Inside the movieclip, there is a text box with words inside. The instance name of the textbox inside radio is called 'radioText' and the instance name of the textbox inside flashlight is called 'flashlightText'. I want the color of the text to turn white when hovering over the movieclip.
The code below works for changing radioText but not flashlightText:
var containers = [radio, flashlight];
for (var i:int = 0; i<containers.length; i++) {
containers[i].addEventListener(MouseEvent.MOUSE_OVER, hOver);
}
var whiteFont:TextFormat = new TextFormat();
whiteFont.color = 0xFFFFFF;
function hOver(evt:Event):void {
evt.currentTarget.radioText.setTextFormat(whiteFont); //change radioText's color
}
what I want to do is instead of
evt.currentTarget.radioText.setTextFormat(whiteFont);
, I want to do somthing like
evt.currentTarget.(currentTarget.name + 'Text').setTextFormat(whiteFont);
but that doesn't work for obvious reasons. Is there a way to do what I want to do?

There are quite a few good ways to implement what you are asking, what you do really depends on how you are setting up your objects.
For example, your pseudo code:
evt.currentTarget.(currentTarget.name + 'Text').setTextFormat(whiteFont);
...could be implemented if you named all your child text fields identically OR if you named them accordingly to some convention (for this example I set a name for the parent and a similar name for the child). So let's assume your container has the name "container" and has a TextField child named "containerText". It would look something like this:
private function hOver(evt:MouseEvent):void {
var n:String = evt.currentTarget.name;
evt.currentTarget.getChildByName( n + "Text" ).setTextFormat( whiteFont );
}
This is now dependent on following a naming convention, which may or may not be ideal. So what might be an even better and more generic way to handle this? You can setup a class for your container object and have a TextField property there. For Example:
class myContainer extends Sprite {
public var textField:TextField;
public function myContainer():void {
textField = new TextField();
addChild(textField);
}
}
Pretty basic, but now if you added all the listeners to types of myContainer your event function could look like this:
private function hOver(evt:MouseEvent):void {
evt.currentTarget[ "textField" ].setTextFormat( whiteFont );
}
Which is probably more what you are looking for. This version allows you to grab the "textField" property of the object you applied the listener to, in this case that property would essentially be your radioText/flashlightText.
Ok so lastly, and the least favorable way to do this, assumes all you care about is that the object has a child of type TextField, it has no logical naming convention, and we are not sure what index it is at in the display list. You would have to do it something like this:
private function hOver(e:MouseEvent):void {
var i:int;
var displayObj:DisplayObjectContainer = e.currentTarget as DisplayObjectContainer;
for ( ; i < displayObj.numChildren; i++ ) {
var obj:* = displayObj.getChildAt( i );
if ( obj is TextField ) {
obj.setTextFormat( whiteFont );
}
}
}
That is also the slowest way of reaching your child object. This should cover all the bases, good luck!

What's wrong with?
DisplayObjectContainer(evt.currentTarget)[evt.currentTarget.name + 'Text'].setTextFormat(whiteFont);

Related

Unable to reference MovieClip inside Button AS3

I have this annoying issue that I hope someone might be able to help me with.
I have a mute button that I created and I have another movieclip inside of that button. All I want it to do is when I toggle the mute the movieclip inside will go to the according frame.
However, every time I try to call the movieclip inside of the button, this error comes up:
Access of possibly undefined property mcMuteToggle through a reference with static type flash.display:SimpleButton.
The instance name for the movieclip within is "mcMuteToggle".
Why not make movieClips that act like buttons?? Since I dont think actual button (simpleButton) types can deal with sub-MovieClips (especially if they too have code). Even if possible don't do it, I can predict a mess whereby Button does things it shouldn't do depending on what code you have in those MClips.
Try an alternate button method, just for a test... You didnt show any test code to work with so I will make assumptions..
1) Make a shape (rectangle?) and convert to MovieClip (or if all coded, then addchild shape to new MovieClip). Let's assume you called it mc_testBtn.
2) Make that MC clickable by coding mc_testBtn.buttonMode = true;
3) Add your mcMuteToggle inside the mc_testBtn
(or by code: mc_testBtn.addChild(mcMuteToggle);
Now you can try something like..
mc_testBtn.addEventListener (MouseEvent.CLICK, toggle_Mute );
function toggle_Mute (evt:MouseEvent) : void
{
if ( whatever condition )
{
mc_testBtn.mcMuteToggle.gotoAndStop(2); //go frame 2
}
else
{
mc_testBtn.mcMuteToggle.gotoAndStop(1); //go frame 1
}
}
This is likely due to strict mode. You can either disable it in the ActionScript settings dialog, access it with a different syntax myButton['mcMuteToggle'], or make a class for the symbol that includes a property mcMuteToggle.
You can also check to make sure the symbol is actually on the stage and that clip is actually in the button:
if('myButton' in root) {
// ...
}
if('mcMuteToggle' in myButton) {
// ...
}
i think u just overwrite that codes. You u can use something like this:
var soundOpen:Boolean = true;
var mySound:Sound = new Sound(new URLRequest("Whatever your sound is"));
var mySc:SoundChannel = new SoundChannel();
var mySt:SoundTransform = new SoundTransform();
mySc = mySound.play();
mcMuteToggle.addEventListener(MouseEvent.CLICK, muteOpenSound);
function muteOpenSound(e:MouseEvent):void
{
if(soundOpen == true)
{
mcMuteToggle.gotoAndStop(2);
/*on frame 2 u need to hold ur soundClose buton so ppl can see :)*/
soundOpen = false;
mySt.volume = 0;
mySc.soundTransfrom = st;
}
else
{
mcMuteToggle.gotoAndStop(1);
soundOpen = true;
mySt.volume = 1;
mySc.soundTransfrom = st;
}
}
This is working for me everytime. Hope u can use it well ;)

How can I detect StaticText in AS3?

I have StaticText fields in my flash project and I need to run some code when the mouse is hovering over them. So I tried this code
stage.addEventListener(MouseEvent.MOUSE_OVER, mouseRollOver);
function mouseRollOver(event:MouseEvent):void {
var tf:StaticText = event.target as StaticText;
if (tf){
//my code
}
}
but it doesn't work. When I use dynamic text fields and replace StaticText with TextField in the var tf, it works fine. I also thought that I could get this thing working with static text fields if I could make the mouse detect not StaticText as a target but some kind of object that has certain text properties (like "selectable" set to true), but I couldn't figure out how to do this. Anyway, I need to detect a static text field as a target somehow. Any help would be appreciated.
Thanks in advance
Your best option would be to put the static text box in a movieclip, and then assign your code based around that. Static text boxes don't have instance names, and can't be manipulated.
It is hard to do this. See this link enter link description here
As you can see you can check if the DisplayObject is StaticText and by checking the mousX and MouseY properties you can find if the rollover is related to this field. By if you use Dynamic text and uncheck selectable field you will get a textfield that acts as StaticField
EDIT
this is an explanation what I mean:
Let we have a StaticText field into stage in Black flash document.
var myFieldLabel:StaticText
var i:uint;
//This for check for all staticFields in state and trace its text. It is possible and it is working. I my case I have only one field and I get reference to it in myFieldLabel:StaticText var. Also I change it's alpha to 0.3.
for (i = 0; i < this.numChildren; i++)
{
var displayitem:DisplayObject = this.getChildAt(i);
if (displayitem instanceof StaticText) {
trace("a static text field is item " + i + " on the display list");
myFieldLabel = StaticText(displayitem);
trace("and contains the text: " + myFieldLabel.text);
trace( myFieldLabel.mouseX);
myFieldLabel.alpha = 0.3;
}
}
//Adds event listener to the stage for mouse move event
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseRollOver);
//This is an event handler. I check if the mouse position is within the static field
function mouseRollOver(evnt:MouseEvent):void
{
if ( 0 <= myFieldLabel.mouseX && myFieldLabel.mouseX <= myFieldLabel.width && 0 <= myFieldLabel.mouseY && myFieldLabel.mouseY <= myFieldLabel.height )
{
mouseOverStaticText( evnt)
}
else
{
mouseNotOverStaticText( evnt)
}
}
// this two methods change the static field alpha. Thay are only to show that is posible to detect and manipulate some properties of the StaticField.
function mouseOverStaticText( evnt)
{
myFieldLabel.alpha = 1;
}
function mouseNotOverStaticText( evnt)
{
myFieldLabel.alpha = 0.3;
}
I'm not sure what is the purpose of the managing of the StaticText field. StaticText is not design to be managed if you have to do something this is almost sure that the field must not be a static - they can be dynamic ( without selectible property ) or can be capsulated with MovieClip or there can be a different solution in your case.

Flash AS3: How to create one function to play sounds from different buttons?

I am making a soundboard and I'm using actionscript. I would like to have one function with the code to play a different sound depending on which button is pressed. I will also be playing from the library rather than a URL. Here is some real code mixed with pseudo for what I want to do:
var soundEffect:SoundEffect = new SoundEffect();
sound1_btn.addEventListener(MouseEvent:CLICK, buttonName, playSoundEffect); //possible?
function playSoundEffect(e:Event, buttonName):void {
soundEffect.attachSound = buttonName + ".mp3" //pseudo code
soundEffect.play();
}
The SoundEffect class is just the name I used in Linkage. I don't know the best way to change the sound that a class represents, or the best way to do this in general. Ideally I'd like to not create 50 different classes with 50 different sound variables and 50 functions. I'd rather each button had some sort of identifier and within the function I can use the button name or identifier to assign the appropriate sound.
If you are using a Button symbol, you could use a naming convention that encodes the class name in your button name.
So if your sound effect class name was sfx_jump , you would name your instance :
sfx_jump_btn
You then set your event listener like this :
sfx_jump_btn.addEventListener(MouseEvent.CLICK, clickHandler);
What you want to do in the clickHandler function is to first generate your className String based on the buttons name property. Then you get the Class Definition via using getDefinitionByName so that you can create an instance of the sound, the following code is how you do that :
public function clickHandler(e:MouseEvent):void
{
var button:SimpleButton = e.target as SimpleButton;
// use replace to clip off the _btn suffix
var className:String = button.name.replace("_btn","");
var SoundClass:Class = getDefinitionByName(className) as Class;
var newSound:Sound = new SoundClass();
newSound.play();
}
You also need to add this import :
import flash.utils.getDefinitionByName;
Yes you can do it. Since you have multiple buttons attach a property to each button like below I attached 'soundToPlay' property to sound1_btn.
sound1_btn.soundToPlay = "1.mp3";
sound1_btn.addEventListener( MouseEvent.CLICK, handleBtnClick);
function handleBtnClick( e:Event ):void{
soundEffect.attachSound = e.target.soundToPlay;
soundEffect.play();
}
#hrehman have the answer for you, but if you button class don't have the property soundToPlay you could use the name property as an ID. and get back with the currentTargetproperty of the event.
sound1_btn.name = "Sound1";
sound1_btn.addEventListener(MouseEvent:CLICK, playSoundEffect);
function playSoundEffect(e:Event):void {
soundEffect.attachSound = e.currentTarget.name + ".mp3";
soundEffect.play();
}

ActionScript 3 name property is not returning the right name...?

I experienced a problem with the name property in as3, I created this "dot" movieclip and I exported to a class,
then I anonymously created a bunch of dots using a loop. I assigned numbers as name to each dots
private function callDots(num:Number):void
{
for (var i = 0; i < subImagesTotal[num]; i++)
{
var d:Dot = new Dot();
d.x = i*23;
d.y = 0;
d.name = i;
dotContainer.addChild(d]);
}
}
so far so good, I checked that if I trace the name here, I will get the number I want.
However, it's not giving me the numbers if I trace it in other functions.
I added all of my dots to "dotContainer", and if I click on one of the dots, it will call this function
private function callFullSub(e:MouseEvent):void
{
var full_loader:Loader = new Loader();
var temp:XMLList = subImages[sub];
var full_url = temp[e.target.name].#IMG;
full_loader.load(new URLRequest(full_url));
full_loader.contentLoaderInfo.addEventListener(Event.INIT, fullLoaded);
}
e.target.name is suppose to be numbers like 1 or 2, but it's giving me "instance66" "instance70" and I
have no idea why. Because I did the same thing with loaders before and it totally worked.
Any ideas? Thanks.
christine
The e.target returns the inner most object clicked on, this could be a TextField, another MovieClip or posibly a shape (I'm not 100% of the last one) inside the "Dot".
To prevent this you could try to set the mouseChildren property to false on the Dot's when you add them. This should insure that nothing inside the dots can dispatch the click event, and thus the Dot's should do it.
Perhaps you could also in the event handler verify the target type with code like this:
private function callFullSub(e:MouseEvent):void
{
if(!e.target is Dot)
throw new Error("target in callFullSub is not Dot but: " + e.target.toString());
//The rest of you code here
}
The answer is [e.currentTarget.name] I perform this all the time!
Should return "Dot1" "Dot2", etc.
If the value you wish to return is a number or other data type other than a string (name of object) use [e.currentTarget.name.substr(3,1).toString()]
Should return 1, 2, etc.
Navee
I tried to reproduce your problem first with Flex using runtime created movieClips and then with Flash using Dot movieClip symbols exported for ActionScript. Neither application exhibited the problem.
You may already know names like "instance66" "instance70" are default enumerated instance names. So, whatever is dispatching the MouseEvent is NOT the dot instance. Perhaps you are unintentionally assigning callFullSub to the wrong targets, maybe your containers? Try assigning it to dot instance right after you create them, like this:
private function callDots(num:Number):void
{
for (var i = 0; i < subImagesTotal[num]; i++)
{
var d:Dot = new Dot();
d.x = i*23;
d.y = 0;
d.name = i;
d.addEventListener(MouseEvent.CLICK, callFullSub);
dotContainer.addChild(d]);
}
}
Be sure to temporarily comment out your original assignment.
Try this might work,..
d.name = i.toString();
You have not shown enough of your code for me to be able to give you a DEFINATE answer, I will however say this.
//After you create each loader you need to set its mouseEnabled
//property to false if you do not want it to be the target of
//Mouse Events, which may be superseding the actual intended target;
var full_loader:Loader = new Loader();
full_loader.mouseEnabled = false;
//Also you could name the loaders and see if what comes back when you click is the same.
ALSO! Add this to your Mouse Event handler for CLICK or MOUSE_DOWN:
trace(e.target is Loader); //If traces true you have an answer
I believe that the mouse events are being dispatched by the Loaders.
please provide more of your code, the code where the Loader.contentLoaderInfo's COMPLETE handler fires. I assume this is where you adding the loaders to the display list as I cannot see that now.

AS3 - How to assign names or tags to loader?

I have a list of images that i’ve loaded with the Loader class, but I’m having a tough time assigning them unique names.
I need unique names because I want to remove certain images after a while.
Is there a way to assign loaders a name or some unique tag so i can remove them later? thanks.
Here's part of my code
for (var i = startnum; i < endnum; i++){
var thumb = panels[i].#THUMB;
var thumb_loader = new Loader();
thumb_loader.load(new URLRequest(thumb));
thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);
thumb_loader.name = i;
thumb_loader.x = (thumb_width + 20)*i;
}
I tried to use getChildByName in another function..
var myLoader:Loader = getChildByName( "1" ) as Loader;
myLoader.unload();
But it's giving me
Error #1009: Cannot access a property or method of a null object reference.
I tried to put thumb_loader as global variable, and do this
var myLoader:Loader = thumb_loader.getChildByName( "1" ) as Loader;
But it's still not working.
Thanks.
All display objects in ActionScript 3 have a name property. Whenever you create a Loader object you can assign a name to it like so:
var myLoader:Loader = new Loader();
myLoader.name = "myUniqueName";
myLoader.load( .... );
addChild( myLoader );
If you'd like to refer to the loader by the name you gave it, use the getChildByName() method.
var myLoader:Loader = getChildByName( "myUniqueName" ) as Loader;
myLoader.unload();
Please be mindful that getChildByName() will only work after you've added the Loader(s) to the display list using addChild(). Otherwise, you'll have to create something to store the references to the Loader objects in, such as an Array and refer to the loaders via that Array. For example, outside your loop you could create an Array named loadersArr. In your loop you would do:
loadersArr["uniqueName"] = thumb_loader;
Then you can refer to your loaders with your unique name through the loadersArr Array.
var loaderToUnload:Loader = loadersArr["uniqueName"];
loaderToUnload.unload();
Without seeing more of your code, its difficult to understand the scope in which this code resides and where any other code that may try to reference these Loaders resides.
Not sure I 100% understand your problem, but why not put them in an object map rather than a list and generate unique names for them if you don't have them...
var img:Image;
var img_map:Object = new Object();
var last_added:int = 0;
for each (img in yourListOfImages)
{
img_map["img_"+last_added] = img;
last_added++;
}
Depending on your environment (Flex or Flash) you can use a UID generator instead of my simplistic unique names above.
package
{
import flash.display.Loader;
public dynamic class DynamicLoader extends Loader
{
public function DynamicLoader()
{
super();
}
}
}
I believe the Loader class is a sealed class so you would want to create this class and use it instead of the normal Loader class to give it any attribute you want. I also believe that without using this DynamicLoader instead of the normal Loader, the Loader class does have the name property available to it.