How to change volume of an array? - actionscript-3

I am trying to make an array of some of my sounds in my game. When a text field is clicked, the volume decreases or increases depending on the value of the number. I have tried doing this, but an error is occurring. What is wrong with my code?
import flash.events.MouseEvent;
import flash.media.SoundChannel;
var onoff:Number;
onoff = 2
var mysoundArray:Array = new Array(tchannel,Mchannel);
var volControl:SoundTransform = mysoundArray.soundTransform;
options_mc.onoff_txt.text = String(onoff);
options_mc.onoff_txt.addEventListener(MouseEvent.CLICK, tick);
function tick(event:MouseEvent)
{
if(onoff == 1)
{
onoff = 2
options_mc.onoff_txt.text = String(onoff);
volControl.volume = .5;
mysoundArray.soundTransform = volControl;
}
else if(onoff == 2)
{
onoff = 1
options_mc.onoff_txt.text = String(onoff);
volControl.volume = 1;
mysoundArray.soundTransform = volControl;
}
}

Your codes have multiple errors.
Error 1: where does tchannel and Mchannel come from?
var mysoundArray:Array = new Array(tchannel,Mchannel);
Error 2: Array mysoundArray does not have child object called soundTransform.
var volControl:SoundTransform = mysoundArray.soundTransform;
Therefore, the object volControl is null. Fix the above errors and your issue will be fixed.

Related

Remove all created symbols from stage

I don't usually do this, but i'm lost here.
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
var first_tile:colors;
var second_tile:colors;
var pause_timer:Timer;
var game_timer:Timer;
var colordeck:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6);
function color_match() {
game_timer = new Timer(10000,1);
for (x=1; x<=4; x++) {
for (y=1; y<=3; y++) {
var random_card = Math.floor(Math.random()*colordeck.length);
var tile:colors = new colors();
tile.col = colordeck[random_card];
colordeck.splice(random_card,1);
tile.gotoAndStop(7);
tile.x = ((x-1)*70)+30;
tile.y = ((y-1)*100)+30;
tile.addEventListener(MouseEvent.CLICK,tile_clicked);
game_timer.addEventListener(TimerEvent.TIMER_COMPLETE,end_game);
addChild(tile);
}
}
game_timer.start();
}
function tile_clicked(event:MouseEvent) {
var clicked:colors = (event.currentTarget as colors);
if (first_tile == null) {
first_tile = clicked;
first_tile.gotoAndStop(clicked.col);
}
else if (second_tile == null && first_tile != clicked) {
second_tile = clicked;
second_tile.gotoAndStop(clicked.col);
if (first_tile.col == second_tile.col) {
pause_timer = new Timer(1000,1);
pause_timer.addEventListener(TimerEvent.TIMER_COMPLETE,remove_tiles);
pause_timer.start();
}
else {
pause_timer = new Timer(1000,1);
pause_timer.addEventListener(TimerEvent.TIMER_COMPLETE,reset_tiles);
pause_timer.start();
}
}
}
function reset_tiles(event:TimerEvent) {
first_tile.gotoAndStop(7);
second_tile.gotoAndStop(7);
first_tile = null;
second_tile = null;
pause_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,reset_tiles);
}
function remove_tiles(event:TimerEvent) {
removeChild(first_tile);
removeChild(second_tile);
first_tile = null;
second_tile = null;
pause_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,remove_tiles);
}
function end_game(event:TimerEvent) {
}
This is a little colour matching game. Click two tiles, they dissappear if matched, or turn back to grey if not. The loop creates instances of colour, in randomly placed pairs, and sets them to frame 7 (grey colour).
I cant work out how to remove any remaining colour blocks when the game time hits zero. Everything i try is throwing errors. The idea is then to let people play again, or a win script.
You don't have to necessarily code it for me, i just need to understand the process! Thanks.
I believe the best way is to create a container, so you can add all tiles and manage them on the best way you decide to.
var tileContainer:Sprite = new Sprite();
addChild(tileContainer);
// instead of addChild(tile);
tileContainer.addChild(tile);
// to remove all tiles
tileContainer.removeChildren();

ScrollPane and ScrollBar not working

I have an application I'm trying to build where it will display a large map image (1920x1040 which is set as the base layer of frame one, then all my AS is on the layer above on the first frame too), then draw lines to it by reading in their coordinates from an external file (lines.txt) and associate a particular image with each line.
When a user clicks on a line, a ScrollPane should open, showing the image associated with the line they clicked on. These images are 1040 in height, and at least 4000px wide, so I want the image to fill the screen height, and then allow the user to use a scroll bar along the bottom to scroll left and right to see the full image.
Right now, I have it working where it reads in my lines.txt file, and draws the lines correctly. Then when I click on a line, it will load the corresponding image in the ScrollPane (along with a button to click that will remove the scroll pane and allow them to select a new line).
However, I can't get a horizontal scroll bar to work. I have it so that the space shows up at the bottom where a scroll bar should be, but there's no bar to drag left/right, and no way to scroll around.
I saw that it's possible to use dragging to scroll, which would be nice, but that hasn't worked either (it' now commented out), and when I have it turned on, when I click my Back Button and attempt to click another line, it throws an error saying,
"TypeError: Error #1009: Cannot access a property or method of a null object reference.
at fl.containers::ScrollPane/endDrag()"
Anybody able to help me clean this up and get it figured out what's going wrong here?
My code:
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.geom.ColorTransform;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import fl.containers.ScrollPane;
import fl.events.ScrollEvent;
import fl.controls.ScrollPolicy;
import fl.controls.DataGrid;
import fl.data.DataProvider;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import fl.controls.UIScrollBar;
import flash.events.Event;
import fl.controls.ScrollBar;
var worldLines:Array = new Array();
var lineSprites:Array = new Array();
var lineSpritesLength:int;
var basicColorTransform:ColorTransform = new ColorTransform();
basicColorTransform.color = 0x00FF00;
var hoverColorTransform:ColorTransform = new ColorTransform();
hoverColorTransform.color = 0xFFFF00;
populateWorldLines();
function populateWorldLines():void
{
var textFile:File = File.applicationDirectory.resolvePath("lines.txt");
var fileContents:String = getFileData(textFile);
var contentsLength:int = fileContents.split("$").length;
for(var i:int = 0; i < contentsLength; i++)
{
trace(i);
worldLines[i] = new Object();
worldLines[i]["x1"] = fileContents.slice(0, fileContents.indexOf(","));
fileContents = fileContents.slice(fileContents.indexOf(",") + 1, fileContents.length);
worldLines[i]["y1"] = fileContents.slice(0, fileContents.indexOf(","));
fileContents = fileContents.slice(fileContents.indexOf(",") + 1, fileContents.length);
worldLines[i]["x2"] = fileContents.slice(0, fileContents.indexOf(","));
fileContents = fileContents.slice(fileContents.indexOf(",") + 1, fileContents.length);
worldLines[i]["y2"] = fileContents.slice(0, fileContents.indexOf(","));
fileContents = fileContents.slice(fileContents.indexOf(",") + 1, fileContents.length);
worldLines[i]["image"] = fileContents.slice(0, fileContents.indexOf(";"));
fileContents = fileContents.slice(fileContents.indexOf("$") + 1, fileContents.length);
}
drawLines(worldLines);
}
function drawLines(lines:Array):void
{
for(var i:int = 0; i < lines.length; i++)
{
var line:Sprite = new Sprite;
line.graphics.moveTo(lines[i]["x1"], lines[i]["y1"]);
line.graphics.lineStyle(3, basicColorTransform.color);
line.graphics.lineTo(lines[i]["x2"], lines[i]["y2"]);
lineSprites.push(line);
addChild(line);
}
lineSpritesLength = lineSprites.length;
this.addEventListener(MouseEvent.MOUSE_OVER, checkLines);
}
function checkLines(e:MouseEvent):void
{
var targetSprite:* = e.target;
for(var i:int = 0; i < lineSpritesLength; i++)
{
if(targetSprite == lineSprites[i])
{
targetSprite.transform.colorTransform = hoverColorTransform;
targetSprite.addEventListener(MouseEvent.CLICK, lineClicked);
targetSprite.addEventListener(MouseEvent.MOUSE_OUT, resetColorTransform);
}
}
}
function lineClicked(e:MouseEvent):void
{
var targetSprite:* = e.target;
for(var i:int = 0; i < lineSpritesLength; i++)
{
if(targetSprite == lineSprites[i])
{
showImage(worldLines[i]["x1"], worldLines[i]["y1"], worldLines[i]["image"]);
}
}
//e.target.removeEventListener(e.type, lineClicked);
}
function showImage(xPos:int, yPos:int, imageName:String):void
{
var aSp:ScrollPane = new ScrollPane();
var aBox:MovieClip = new MovieClip();
drawBox(aBox, imageName);
aSp.source = aBox;
aSp.setSize(1920, 1040);
aSp.move(0, 0);
aSp.name = "scrollyPaneThing";
//aSp.scrollDrag = true;
aSp.horizontalScrollPolicy=ScrollPolicy.ON;
aSp.addEventListener(ScrollEvent.SCROLL, scrollListener);
addChild(aSp);
}
function scrollListener(event:ScrollEvent):void {
var mySP:ScrollPane = event.currentTarget as ScrollPane;
trace("scrolling");
trace("\t" + "direction:", event.direction);
trace("\t" + "position:", event.position);
trace("\t" + "horizontalScrollPosition:", mySP.horizontalScrollPosition, "of", mySP.maxHorizontalScrollPosition);
trace("\t" + "verticalScrollPosition:", mySP.verticalScrollPosition, "of", mySP.maxVerticalScrollPosition);
};
function drawBox(box:MovieClip,imageName:String):void {
trace(imageName + ":imageName");
var file:File = File.applicationDirectory.resolvePath("dataImages/"+imageName);
var imageLoader:Loader = new Loader();
var image:URLRequest = new URLRequest(file.url);
imageLoader.load(image);
imageLoader.x = 1;
imageLoader.y = 1;
box.addChild (imageLoader);
trace("backButton.png:imageName");
var file2:File = File.applicationDirectory.resolvePath("backButton.png");
var imageLoader2:Loader = new Loader();
var image2:URLRequest = new URLRequest(file2.url);
imageLoader2.load(image2);
imageLoader2.x = 10;
imageLoader2.y = 950;
box.addChild (imageLoader2);
imageLoader2.addEventListener(MouseEvent.CLICK, removeScrollyPaneThing);
}
function removeScrollyPaneThing(MouseEvent):void
{
removeChild(getChildByName("scrollyPaneThing"));
}
function resetColorTransform(e:MouseEvent):void
{
e.target.transform.colorTransform = basicColorTransform;
e.target.removeEventListener(e.type, resetColorTransform);
}
function getFileData(file:File):String
{
var fDataStream:FileStream;
var sContent:String;
fDataStream = new FileStream();
fDataStream.open(file, FileMode.READ);
sContent = fDataStream.readUTFBytes(fDataStream.bytesAvailable);
fDataStream.close();
return sContent;
}
Your Loader Object has a scrollRect property that is built in.
It is MUCH easier to use a simple ScrollBar than a ScrollPane,
but mouse dragging is much cleaner:
see: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#scrollRect
To mouse drag:
private var scrollyThingy:Rectangle;
private var map:Loader;
// holders for the location of the view
//(to allow for cancelling the drag):
private var _cx:int = 0;
private var _cy:int = 0;
private var downpoint:Point = null;
public function init():void{
// Load your image:
/* I prefer to use embeded png files
or draw simple line images, but
Loader objects also have a scrollRect property
From this point I will assume your main image ('map') is loaded,
and 'scrollyThingy' is the part you want diplayed
I could not follow the code once you added the
loader to the stage very well...
*/
// to enable mouse dragging:
map.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
var w:int = 100;
var h:int = 100;
scrollyThingy = new Rectangle(_cx, _cy, w, h);
map.scrollRect = scrollyThingy;
AddChild(map);
}
private function onMouseDown(event:MouseEvent):void{
_downpoint = new Point(event.stageX, event.stageY);
map.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
map.addEventListener(MouseEvent.MOUSE_DRAG, onMouseDrag);
map.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
map.addEventListener(MouseEvent.RELEASE_OUTSIDE , onReleaseOutside);
}
private function onMouseDrag(event:MouseEvent):void{
if (_downpoint == null)
return;
// the movement delta:
_dx = int((event.stageX - _downpoint.x));
_dy = int((event.stageY - _downpoint.y));
// (if the movement is backwards, use scrollyThingy.x -= _dx)
scrollyThingy.x += _dx;
scrollyThingy.y += _dy;
Loader.scrollRect = scrollyThingy;
}
private function onMouseUp(event:MouseEvent):void{
if (_downpoint == null)
return;
// new corner coords
_cx += int((event.stageX - _downpoint.x));
_cy += int((event.stageY - _downpoint.y));
resetListeners();
}
private function onReleaseOutside(event:MouseEvent):void{
// put it back where it was
resetListeners();
}
private function resetListeners():void{
scrollyThingy.x = _cx;
scrollyThingy.y = _cy;
Loader.scrollRect = scrollyThingy;
_downpoint = null;
if(!map.hasEventListener(MouseEvent.MOUSE_DOWN)
map.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
//(if it has one, it has them all!)
if(map.hasEventListener(MouseEvent.MOUSE_DRAG){
map.removeEventListener(MouseEvent.MOUSE_DRAG, onMouseDrag);
map.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
map.removeEventListener(MouseEvent.RELEASE_OUTSIDE , onReleaseOutside);
}
}
if you still want a ScrollBar, just scale it to your Loader dimensions less the
size of the viewport (xScrollBar.maximum = loader.content.width - scrollyThingy.width,
yScrollbar.maximum = loader.content.height - scrollyThingy.height) then you can use the
same listener for both bars:
function onScrollBarChange(e:event):void{
scrollyThingy.x = xScrollBar.value;
scrollyThingy.y = yScrollBar.value;
}
listen for a change Event and set the Loader.scrollRect.x and Loader.scrollRect.y
properties to the scrollBarx.value & scrollBary.value.
Note also that I did not include any value checking.
You should check the values before moving the scrollRect
to avoid rangeErrors
i.e. if (_cx > loader.width - loader.scrollRect.width)
_cx = Loader.width - Loader.scrollRect.width;

Issue with sharedObject usage / loading data

The main goal of my code is to create a 3x3 grid and when you click a cell from that grid you cant click it again even if you close the fla and load it again.
Something like a shop where the 1st row is level1 of the upgrade and the columns are the other levels.
There are also 2-3 other things that it does -> every cell of the grid has 4 mouseStates.
Also at the 1st load of the FLA you create the 3x3 grid and you can click only on the elements in the 1st row.(you cant get Speed 2 if you didnt have Speed1 before that.)
So you can click the 2nd element of a column only if the 1st element of the same column has been clicked before.
The same goes for the 3rd element of the column -> it can be clicked only if the 2nd was clicked before.
But im having trouble with the logic after loading the fla for the 2nd time.
To be more specific :
It is changing the mouseOver/out states on the elements that were clicked before(which is good (cause i want to see that)), but it is leting me click only the 1st row.And since Im loading the clickedBefore buttons and removing the mouseEvent.CLICK from them, I cant click some of them if i haven`t clicked them at the 1st load of the fla.
I have 2 classes: Main
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Graphics;
import flash.display.Bitmap;
import flash.display.SimpleButton;
import flash.net.SharedObject;
public class Main extends Sprite
{
private var elementRow:int = 0;
private var elementCol:int = 0;
private var myClassImage_Arr:Array = new Array();//this contains the different mouseState Images in Class data.
private var myBitmapNames_Arr:Array = ["speed1_", "speed2_", "speed3_",
"time1_", "time2_", "time3_",
"turbo1_", "turbo2_", "turbo3_",];
//------------------------------------------
private var index:int = 0;
private var col:int = 3;
private var row:int = 3;
//------------------------------------------
private var savedData:SharedObject = SharedObject.getLocal("ZZZ_newWAY_nextButton+imageChange_7");
private var buttonThatHaveBeenClicked_Arr:Array = [];
private var myButtons_Arr:Array = [];
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
for (var i:int = 0; i < col; i++)
{
var lastRowElement:BitmapButton = null;
for (var j:int = 0; j < row; j++)
{
for (var k:int = 0; k < 4; k++)//4states of mouse
{
var cls:Class = Class(getDefinitionByName(myBitmapNames_Arr[index] + k));
myClassImage_Arr.push(cls);
}
var myImage_mc = new BitmapButton(myClassImage_Arr[0 + (index * 4)],
myClassImage_Arr[1 + (index * 4)],
myClassImage_Arr[2 + (index * 4)],
myClassImage_Arr[3 + (index * 4)], i, j);
myImage_mc.x = 100 + i * (myImage_mc.width + 10);
myImage_mc.y = 100 + j * (myImage_mc.height + 10);
myImage_mc.name = "myImage_mc" + index;
this.addChild(myImage_mc);
myButtons_Arr.push(myImage_mc)
myImage_mc.mouseEnabled = false;
myImage_mc.mouseChildren = false;
myImage_mc.buttonMode = false;
myImage_mc.addEventListener("send_SOS", onCustomClick);
if ( lastRowElement == null )
{
myImage_mc.mouseEnabled = true;
myImage_mc.mouseChildren = true;
myImage_mc.buttonMode = true;
}
else
{
lastRowElement.next_1 = myImage_mc;
}
lastRowElement = myImage_mc;
index++;
}
}
if(savedData.data.myArray == undefined) trace(" 1st time loading this game\n")
else if(savedData.data.myArray != undefined)
{
trace(" Game was played before\n")
buttonThatHaveBeenClicked_Arr = savedData.data.myArray;
var savedData_length:int = savedData.data.myArray.length;
trace("Buttons that have been clicked before: " + buttonThatHaveBeenClicked_Arr + "\n");
for (var m:int = 0; m < myButtons_Arr.length; m++)
{
var myButtons_ArrName:String = myButtons_Arr[m].name
for (var p:int = 0; p < savedData_length; p++)
{
if(myButtons_ArrName == savedData.data.myArray[p])
{
myButtons_Arr[m].alpha = 0.9
myButtons_Arr[m].buttonMode = false;
myButtons_Arr[m].removeEventListener("send_SOS", onCustomClick);
myButtons_Arr[m].myInsideBtn.upState = myButtons_Arr[m].image3
myButtons_Arr[m].myInsideBtn.overState = myButtons_Arr[m].image4
}
}
}
}
}
private function onCustomClick(ev:Event):void
{
trace(ev.target.name);
if (ev.target is BitmapButton)
{
var btn:BitmapButton = ev.currentTarget as BitmapButton;
if (btn.next_1 != null)
{
btn.next_1.mouseEnabled = true;
btn.next_1.mouseChildren = true;
btn.next_1.buttonMode = true;
}
btn.mouseChildren = false;
btn.buttonMode = false;
btn.removeEventListener("send_SOS", onCustomClick);
buttonThatHaveBeenClicked_Arr.push( btn.name );
savedData.data.myArray = buttonThatHaveBeenClicked_Arr;
savedData.flush();
savedData.close();
}
}
}
}
and BitmapButton
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.Event;
public class BitmapButton extends Sprite
{
public var next_1:BitmapButton = null;
//-----------------------------------
public var myInsideBtn:SimpleButton = new SimpleButton();
private var image1:Bitmap;
private var image2:Bitmap;
public var image3:Bitmap;
public var image4:Bitmap;
public var imageIsInRow:int;
public var imageIsInCol:int;
public function BitmapButton(active_OutState:Class, active_OverState:Class, notActive_OutState:Class, notActive_OverState:Class,col:int,row:int)
{
image1 = new Bitmap (new active_OutState() );
image2 = new Bitmap (new active_OverState() );
image3 = new Bitmap (new notActive_OutState() );
image4 = new Bitmap (new notActive_OverState() );
imageIsInRow = row;
imageIsInCol = col;
myInsideBtn.upState = image1;
myInsideBtn.overState = image2;
myInsideBtn.downState = myInsideBtn.upState;
myInsideBtn.hitTestState = myInsideBtn.overState;
addChild( myInsideBtn );
myInsideBtn.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(ev:MouseEvent):void
{
myInsideBtn.upState = image3;
myInsideBtn.overState = image4;
var myNewEvent:Event = new Event("send_SOS");
this.dispatchEvent(myNewEvent);
trace("CLICK from inside the button");
}
}
}
ill also upload it to this link Grid_with_sharedObject with a zip.
and upload also Grod_before_Using_sharedObject if someone decides that he would help but the code is to messed up
If I'm reading your code correctly, I'd honestly say your problem is sequential. For whatever reason, the setting of the active and inactive rows is occurring BEFORE the data is actually being interpreted into the button states. As a result, the computer sees all buttons as off when it decides whether to make other rows clickable, and THEN updates the state of the buttons.
The easiest way to fix this, I think, would be to split the Main() function into a few sub functions, such as updateButtons() for the function that changes whether a row/button is clickable, and loadData() for the function the loads from the SharedObject. In Main(), put the calls to those functions. This will make Main() easier to work with, and you can call a function multiple times if necessary.
To solve your particular issue, you'd need to get the data for the buttons using the SharedObject FIRST (which obviously is working), and THEN update whether the other buttons are clickable.
A "soft-skills" tip for programming: when you run into a problem, grab a piece of paper, a pencil, and read through your code the way your computer would. Be the computer. Write down variables and their values when they change. Mark when functions are called. You'll spot a lot of errors this way.

AS3 / Displaying textField on movieClip with a Vector

I wanted to place a textField on a movieClip so i used:
vec[0].addChild(text1);
If I use that there comes an error. Or should i make a new Vector?
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at FQuiz_fla::MainTimeline/frame1()
>
Move your text field declaration portion to top, that is before your add child method.
import flash.display.MovieClip; import flash.events.Event; import flash.display.SimpleButton; import flash.text.TextField; import flash.events.MouseEvent;
var volgende:Volgende = new Volgende(); volgende.x = 663; volgende.y = 546; volgende.visible = true; volgende.useHandCursor = true; addChild(volgende);
var vec:Vector. = new Vector.
vec[0] = new Vraag1(); vec[1] = new Vraag2();
var tekstveld1:TextField = new TextField();
tekstveld1.antiAliasType = AntiAliasType.ADVANCED; tekstveld1.text = "" tekstveld1.type = TextFieldType.INPUT; tekstveld1.textColor = 0xEC8DAD; tekstveld1.width = 390; tekstveld1.height = 248; tekstveld1.x = 165; tekstveld1.y = 312; tekstveld1.border = false; tekstveld1.borderColor = 0xDA1C5C; tekstveld1.wordWrap = true; tekstveld1.restrict = "A-Za-z0-9";
vec[1].addChild(tekstveld1);
addChild(vec[0]); //add one of the MovieClips to stage
volgende.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void { for(var i:int = 0; i < vec.length; i++) //go through the Vector one by one { if(contains(vec[i])) //if the Object at position i in the Vector is on stage { removeChild(vec[i]); //remove the Object var next:int = i; //create a temporary holder if(next == vec.length) //check if the displayed Object was the last in the list { next = 1; //if so, set to 0 }else{ next++; //otherwise, only add 1 } addChild(vec[next]); //add the next Object to the stage. If the removed Object was the last in the Vector, it'll add the first Object in the Vector to the list break; //escape the for loop, otherwise it'll always only show the last Object }
} }
Hope it helps. Me too on mobile ;)
import flash.text.TextField;
var vec:Vector.<MovieClip> = new Vector.<MovieClip>
vec[0] = new Start();
var text1:TextField = new TextField();
text1.text = "ramesh";
vec[0].addChild(text1);
addChild(vec[0]); //add one of the MovieClips to stage
This should work.

Cannot access null object reference for RadioButtonGroup

Quick version:
When trying to compare 2 RadioButtonGroups with an if statement, if one of the groups does not have a RadioButton selected, I get an error;
Error #1009: Cannot access a property or method of a null object reference.
Long version:
I am creating 2 lists in actionscript that have the same content and have stored them in RadioButtonGroups. The idea is that a user will choose an element from column A and then select an element from column B. This functionality works fine, but when I do validation where the program checks when clicking a button if both columns have been selected, I get:
Cannot access property error (See above).
Here is my code:
import fl.controls.RadioButtonGroup;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import fl.controls.RadioButton;
var focus1:RadioButtonGroup = new RadioButtonGroup("Focus 1");
var focus2:RadioButtonGroup = new RadioButtonGroup("Focus 2");
var myXML:XML;
var myLoader:URLLoader = new URLLoader();
var btn1:Array = new Array();
var btn2:Array = new Array();
myLoader.load(new URLRequest("courseLoader.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
for (var i = 0; i < myXML.COURSES.length(); i++) {
var radA:RadioButton = new RadioButton();
var radB:RadioButton = new RadioButton();
// Create left focus column
radA.x = 50;
radA.y = i * 25 + 75;
radA.width = 300;
radA.name = "radA" + i;
radA.label = myXML.COURSES[i].NAME[0];
addChild(radA);
btn1.push(radA);
btn1[i].group = focus1;
// Create right focus column
radB. x = 450;
radB.y = i * 25 + 75;
radB.width = 300;
radB.name = "radB" + i;
radB.label = myXML.COURSES[i].NAME[0];
addChild(radB);
btn2.push(radB);
btn2[i].group = focus2;
}
submit_btn.addEventListener(MouseEvent.CLICK, checkResult);
function checkResult(e:MouseEvent):void {
var tempVar
if (focus1.selection.label == focus2.selection.label) {
feedback.text = "Nope, they're both the same. Try again";
} /* THIS IS WHERE IT STOPS WORKING */ else if (focus1.selection == null) {
feedback.text = "You forgot to choose a focus from the 2nd column!";
} else if (focus1.selection.label == null) {
feedback.text = "You forgot to choose a focus from the 1st column!";
} else if (focus2.selection.label == null) {
feedback.text = "You forgot to choose a focuse from the 2nd column!";
}
}
I've tried using different kinds of properties and methods for comparing both groups and checking if one of them is not selected but I keep getting the same error.
You first are checking for labels, and only THEN you check if selection is null. This is wrong, you have to do it in reverse order.
if (focus1.selection == null) {
feedback.text = "You forgot to choose a focus from the 1st column!";
} else if (focus2.selection == null) {
feedback.text = "You forgot to choose a focus from the 2nd column!";
} else if (focus1.selection.label == focus2.selection.label) {
feedback.text = "Nope, they're both the same. Try again";
}