AS3 Cannot access a property or method of null object reference, issue with gotoAndPlay - actionscript-3

so I'm still fairly new to AS3 and I'm getting my head around the errors and stuff and I'm trying to figure out why this is not working how it should, the function still executes but it leaves an error on my console. Here is my code:
import flash.events.MouseEvent;
import flash.display.MovieClip;
stop();
var activeHitArray:Array = new Array(word_select_box);
var activeDropArray:Array = new Array(answer1_word, answer2_word, answer3_word);
var hitPositionsArray: Array = new Array();
for (var numi:int = 0; numi < activeDropArray.length; numi++) {
activeDropArray[numi].buttonMode = true;
activeDropArray[numi].addEventListener(MouseEvent.MOUSE_DOWN, mousedown1);
activeDropArray[numi].addEventListener(MouseEvent.MOUSE_UP, mouseup1);
hitPositionsArray.push({xPos:activeDropArray[numi].x, yPos:activeDropArray[numi].y});
}
function mousedown1(event:MouseEvent):void {
event.currentTarget.startDrag();
setChildIndex(MovieClip(event.currentTarget), numChildren - 1);
}
function mouseup1(event:MouseEvent):void {
var dropindex1:int = activeDropArray.indexOf(event.currentTarget);
var target:MovieClip = event.currentTarget as MovieClip;
target.stopDrag();
if(target.hitTestObject(activeDropArray[dropindex1])){
// target.x = activeHitArray[dropindex1].x;
//target.y = activeHitArray[dropindex1].y;
if(answer1_word.hitTestObject(word_select_box)){
gotoAndStop("6");
}
} else {
target.x = hitPositionsArray[dropindex1].xPos;
target.y = hitPositionsArray[dropindex1].yPos;
}
}
And the Error I'm getting through is:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at game_flv_fla::MainTimeline/frame6()
at flash.display::MovieClip/gotoAndStop()
at game_flv_fla::MainTimeline/mouseup1()
The only thing I can think of is that it is something to do with the gotoAndPlay() because when I place a trace into it's place I get no errors.

I copied your code, compiled and lauched it in Flash IDE. It works! :)
There were no errors.
But I know where the isue may lay. The addEventListeners are still on, no matter if there still are the objects they were linked to. You need to clean all active things before going to next frame:
if(target.hitTestObject(activeDropArray[dropindex1])){
if(answer1_word.hitTestObject(word_select_box)){
for (var i:uint = 0; i < activeDropArray.length; i++) {
activeDropArray[i].removeEventListener(MouseEvent.MOUSE_DOWN, mousedown1);
activeDropArray[i].removeEventListener(MouseEvent.MOUSE_UP, mouseup1);
}
gotoAndStop("6");
}
}

Related

cannot convert flash.display::Stage#2a2cdf99 to flash.display.MovieClip?

So I'm creating a platform game in Actionscript 3.0, trying to call a function that spawns blocks based on an array. The code is in a 'Game' class and is directed towards a movieclip on my .fla
When it is ran I get the error:
"cannot convert flash.display::Stage#2a2cdf99 to flash.display.MovieClip."
Here's the code:
public function GameScreen(stageRef:Stage = null )
{
this.stageRef = stageRef;
btnReturn.addEventListener(MouseEvent.MOUSE_DOWN, returnMainMenu, false, 0, true);
mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
this.addEventListener(Event.ENTER_FRAME, createLvl);
this.stageRef.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
this.stageRef.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
this.stageRef.addChild(blockHolder);
}
And
private function createLvl(event:Event):void
{
var lvlArray:Array = MovieClip(root)['lvlArray' +lvlCurrent];
var lvlColumns:int = Math.ceil(lvlArray.length/16);
for(var i:int = 0;i<lvlArray.length;i++){
if(lvlArray[i] == 1){
if(i/lvlColumns == int(i/lvlColumns)){
row ++;
}
var newBlock:Block = new Block();
newBlock.graphics.beginFill(0xFFFFFF);
newBlock.graphics.drawRect(0,0,50,50);
newBlock.x = (i-(row-1)*lvlColumns)*newBlock.width;
newBlock.y = (row - 1)*newBlock.height;
blockHolder.addChild(newBlock);
} else if (lvlArray[i] == 'MAIN'){
mcMain.x = (i-(row-1)*lvlColumns)*newBlock.width;
mcMain.y = (row-1)*newBlock.height;
}
}
row = 0;
}
Please help =(
Thanks!
First of all:
Turn on "permit debugging" in your publish settings. This will give you line numbers with your errors, so you can determine the exact location of your error.
Post the entire stack trace. That error by itself is not a lot to go on.
Given the error and the code you've posted, the error must be caused by your use of MovieClip(root). The root property does not always point to the main timeline in Flash, it will point to the Stage if the display object is added directly to the stage. For example:
trace(stage.addChild(new Sprite()).root) // [object Stage]
Documentation on root: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#root

as3 1119: Access of possibly undefined property getters/setters

It would be amazing if someone could expand on the current answer, Thanks.
full error
Line 22 1119: Access of possibly undefined property CharacterX through a reference with static type flash.display:DisplayObject.
I'm trying to set a variable for the object shark, that is already defined in the object character
First time using setters in flash, so I might not be doing this right.
code I'm using to set the variable I tried to comment out the stuff I thought was irrelevant to this issue, not actually commented out in real code.
var character:Character;
//var bullet:Bullet=null;
//var bullets:Array = new Array();
//var enemies:Array = new Array();
//character=new Character(bullets);
addChild(character);
var shark:Shark=new Shark();
addChild(shark);
//var enemy:Enemy=null;
////var i:int;
//for (i=0; i<10; i++) {
//enemy = new Enemy(Math.random()*stage.stageWidth, Math.random()*stage.stageHeight);
//addChild(enemy);
// enemies.push(enemy);
//}
//stage.addEventListener(Event.ENTER_FRAME, colTest);
//function colTest(e:Event ):void {
// if(character.hitTestObject(turtle)){
// character.gotoAndStop("Turtle");
// }
//}
shark.setT(character.x, character.y)
class in which I'm attempting to define a variable using the function above.
package
{
import flash.display.*;
import flash.events.*;
public class Shark extends MovieClip
{
var CharacterX:Number = 0;
var CharacterY:Number = 0;
public function Shark()
{
this.x = 300;
this.y = 200;
addEventListener(Event.ENTER_FRAME,playGame);
}
public function setT(characterx:Number,charactery:Number){
CharacterX = characterx - this.x;
CharacterY = charactery - this.y;
}
function playGame(event:Event):void
{
var ease:int = 20;
var speed:int = 10;
var targetX:int = root.CharacterX - this.x;
var targetY:int = root.CharacterY - this.y;
var rotation = Math.atan2(targetY,targetX) * 180 / Math.PI;
cut code off here, didn't want to make a code dump can get you anything that might be relevant just ask.
Here is a pastebin of all of the code if it might help,
Shark class:
Actions on Frame 1:
Character class
Let me start by saying I can't spot the exact problem here, but I have some ideas. Your error 1999 says that something of the type display object is trying to change your variable. This happens a lot when you use parent.myMethod() because parent is typed as display object. You would fix this by typecasting like (parent as MovieClip).myMethod
In your case I don't see the exact source of this problem. But you could try using this.characterX in your setT function

Possible misuse of evt.target.name. "Error #1010: A term is undefined and has no properties."

So far this program is supposed to make an child object visible when the parent object is moused over, but I can't seem to get it to work. I'm in a little over my head here. Here's my code:
var iconCompArray:Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_MOVE, moveMouse);
addIcons();
function addIcons():void
{
var iconComp:IconComp = new IconComp();
iconComp.x = stage.stageWidth/4;
iconComp.y = stage.stageHeight/4;
iconComp.iconImage.gotoAndStop(2);
iconComp.iconHighlight.visible = false;
iconComp.iconTitle.text = "Program X";
iconCompArray.push(iconComp);
addChild(iconComp);
}
function moveMouse(evt:MouseEvent):void
{
for (var i:int = 0; i < iconCompArray.length; i++)
{
if (evt.target.name == iconCompArray[i])
{
iconCompArray[i].iconHighlight.visible = true;
}
}
}
A new "iconComp" is pulled from the library and added to the stage through the iconCompArray. The idea was that when you mouse over the icon, a blue box would appear around it (iconHighlight.visible). But for some reason, what I have here doesn't work. I think I may have used evt.target.name incorrectly but I can't find a solution. Here's the error message that appears in the output:
TypeError: Error #1010: A term is undefined and has no properties.
at as3_fla::MainTimeline/addIcons()
at as3_fla::MainTimeline/frame1()
From the error you get the problem seems to be in the addIcons functions. You should check that the name of all your movie clip's childs is correct. The movie clip's property mouseChildren should be set to false. Also, it would be probably better if you use MOUSE_OVER and MOUSE_OUT events instead of MOUSE_MOVE.
function addIcons():void
{
var iconComp:IconComp = new IconComp();
iconComp.x = stage.stageWidth / 4;
iconComp.y = stage.stageHeight / 4;
iconComp.iconImage.gotoAndStop(2);
iconComp.iconHighlight.visible = false;
iconComp.iconTitle.text = "Program X";
iconComp.mouseChildren = false;
iconComp.addEventListener(MouseEvent.MOUSE_OVER, onIconOver);
iconComp.addEventListener(MouseEvent.MOUSE_OUT, onIconOut);
iconCompArray.push(iconComp);
addChild(iconComp);
}
And the event listeners should look like this:
function onIconOver(evt:MouseEvent):void {
IconComp(evt.target).iconHighlight.visible = true;
}
function onIconOut(evt:MouseEvent):void {
IconComp(evt.target).iconHighlight.visible = false;
}
You can also see the line of code that gives you that error if youy publish the swf in debug mode (Ctrl+Shift+Enter).

Remove the clicked objects

I'm trying to remove the array objects that are being clicked and add them into another array to display them else where. I posted the current code.
I think the problem maybe with .currentTarget. I tried replacing the .currentTarget to .target but the function wasn't getting past this line : if (socket_Array[i] == in_event.target) (in this version its .currentTarget, I am just saying when I tried changing it to .target)
The error I get is this:
TypeError: Error #1034: Type Coercion failed: cannot convert []#2c2a8f11 to flash.display.DisplayObject.
Function that creates the objects:
function createSockets():void
{
var socket_one:socket = new socket ();
var socket_two: socketyellow = new socketyellow ();
var socket_three: socketdarkorange = new socketdarkorange ();
var socket_four: socketlightgreen= new socketlightgreen ();
var socket_five: socketpurple = new socketpurple ();
var socket_six: socketdarkgreen = new socketdarkgreen ();
socket_Array.push(socket_one, socket_two,socket_three, socket_four, socket_five, socket_six);
for (var i:int=0; i<socket_Array.length; i++)
{
addChild(socket_Array[i]);
socket_Array [i].x = socket_x_position;
socket_Array [i].y = socket_y_position;
socket_Array[i].addEventListener(MouseEvent.MOUSE_DOWN, removeItemOnClick);
}
temp_update ();
}
Function that is suppose to get rid of the object clicked and add it to an array.
function removeItemOnClick(in_event:MouseEvent):void
{
var i:int = 0;
for (i=0; i<socket_Array.length; i++)
{
if (socket_Array[i] == in_event.currentTarget)
{
trace ("it goes here");
var removed = socket_Array.splice(i, 1);
trace (removed);
trace (socket_Array );
var drop:Sprite = in_event.currentTarget as Sprite;
removeChild (drop);
removedItem[removedItem.length] = removed;
createremovedItem ();
trace (removedItem);
updateDisplay ();
choice_updateDisplay ();
}
}
}
var removedItem_position = 0
function createremovedItem () {
for (removedItem_position; removedItem_position<removedItem.length; removedItem_position++){
addChild (removedItem [removedItem_position]);
}
}
First of all, .currentTarget is correct.
Secondly, there's no point in calling removeChild() and then calling addChild(). The net effect of both calls is nothing.
Almost all of the code in the second function is unnecessary. Here's a shorter version:
function removeItemOnClick(in_event:MouseEvent):void {
var index:int = socket_Array.indexOf(in_event.currentTarget);
var drop:Sprite = socket_Array.splice(index,1) as Sprite;
removedItem.push(drop);
updateDisplay();
choice_updateDisplay();
}
If you want to display the new item elsewhere, just change drop.x and drop.y.
As the error suggests it looks like it is problem with type coercion.
Try to replace the condition of your if statement with this:
if (DisplayObject(socket_Array[i]) == DisplayObject(in_event.currentTarget))
In case this is not working your might have more information while debugging by storing the two objects you want to compare into temporary variables

Multiple movieclips all go to the same spot; What am i doing wrong?

So I'm trying to shoot multiple bullets out of my body and it all works except I have an odd problem of just one bullet showing up and updating to set position for the new ones.
I have a move able player thats supposed to shoot and I test this code by moving the player and shooting. Im taking it step by step in creating this.
The result of tracing the bulletContainer counts correctly in that its telling me that movieclips ARE being added to the stage; I Just know it comes down to some kind of logic that im forgetting.
Here's My Code (The Bullet it self is a class)
UPDATE*
Everything in this code works fine except for I stated earlier some code seems reduntned because I've resorted to a different approaches.
BulletGod Class:
public class bulletGod extends MovieClip{
//Register Variables
//~Global
var globalPath = "http://127.0.0.1/fleshvirusv3/serverside/"
//~MovieCLips
var newBullet:bulletClass = new bulletClass();
//~Boolean
var loadingBulletInProgress:Number = 0;
var shootingWeapon:Number = 0;
//~Timers
var fireBulletsInterval = setInterval(fireBullets, 1);
var bulletFireEvent;
//~Arrays
var bulletArray:Array = new Array();
var bulletType:Array = new Array();
var bulletContainer:Array = new Array();
//~Networking
var netBulletRequest:URLRequest = new URLRequest(globalPath+"bullets.php");
var netBulletVariables:URLVariables = new URLVariables();
var netBulletLoader:URLLoader = new URLLoader();
//~Bullet Image Loader
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest();
public function bulletGod() {
//Load every bullet for every gun
//Compile data to be requested
netBulletVariables.act = "loadBullets"
netBulletRequest.method = URLRequestMethod.POST
netBulletRequest.data = netBulletVariables;
netBulletLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
netBulletLoader.addEventListener(Event.COMPLETE, getBulletImages);
netBulletLoader.load(netBulletRequest);
}
private function getBulletImages(bulletImageData:Event){
//Request every bullet URL image
//Set vars
var bulletData = bulletImageData.target.data;
//Load images
for(var i:Number = 0; i < bulletData.numBullets; i++){
bulletArray.push(bulletData["id"+i.toString()]);
bulletType.push(bulletData["bullet"+i.toString()]);
//trace(bulletData["id"+i]+"-"+bulletData["bullet"+i]);
}
//All the arrays have been set start firing the image loader/replacer
var imageLoaderInterval = setInterval(imageReplacer, 10);
}
private function imageReplacer(){
//Check to see which image needs replacing
if(!loadingBulletInProgress){
//Begin loading the next image
//Search for the next "String" in the bulletType:Array, and replace it with an image
for(var i:Number = 0; i < bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//Load this image
mRequest = new URLRequest(globalPath+"ammo/"+bulletType[i]);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImage);
mLoader.load(mRequest);
//Stop imageReplacer() while we load image
loadingBulletInProgress = 1;
//Stop this for() loop while we load image
i = 999;
}
}
}
}
private function loadImage(BlackHole:Event){
//Image has loaded; find which array slot it needs to go into
for(var i:Number = 0; i <= bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//We found which array type it belongs to; now replace the text/url location with the actual image data
var tmpNewBullet:MovieClip = new MovieClip;
tmpNewBullet.addChild(mLoader);
//Add image to array
bulletType[i] = tmpNewBullet;
//Restart loadingBullets if there are more left
loadingBulletInProgress = 0;
//Stop for() loop
i = 999;
}
}
}
//###############################################################################################################################################
private function fireBullets(){
//If player is holding down mouse; Fire weapon at rate of fire.
if(shootingWeapon >= 1){
if(bulletFireEvent == null){
//Start shooting bullets
bulletFireEvent = setInterval(allowShooting, 500);
}
}
if(shootingWeapon == 0){
//The user is not shooting so stop all bullets from firing
if(bulletFireEvent != null){
//Strop firing bullets
clearInterval(bulletFireEvent);
bulletFireEvent = null
}
}
}
private function allowShooting(){
//This function actually adds the bullets on screen
//Search for correct bullet/ammo image to attach
var bulletId:Number = 0;
for(var i:Number = 0; i < bulletArray.length; i++){
if(bulletArray[i] == shootingWeapon){
//Bullet found
bulletId = i;
//End For() loop
i = 999;
}
}
//Create new bullet
//Create Tmp Bullet
var tmpBulletId:MovieClip = new MovieClip
tmpBulletId.addChild(newBullet);
tmpBulletId.addChild(bulletType[bulletId]);
//Add To Stage
addChild(tmpBulletId)
bulletContainer.push(tmpBulletId); //Add to array of bullets
//Orientate this bullet from players body
var bulletTmpId:Number = bulletContainer.length
bulletTmpId--;
bulletContainer[bulletTmpId].x = Object(root).localSurvivor.x
bulletContainer[bulletTmpId].y = Object(root).localSurvivor.y
//addChild(bulletContainer[bulletTmpId]);
}
//_______________EXTERNAL EVENTS_______________________
public function fireBullet(weaponId:Number){
shootingWeapon = weaponId;
}
public function stopFireBullets(){
shootingWeapon = 0;
}
}
}
BulletClass:
package com{
import flash.display.*
import flash.utils.*
import flash.net.*
import flash.events.*
public class bulletClass extends MovieClip {
public var damage:Number = 0;
public function bulletClass() {
//SOME MOVEMENT CODE HERE
}
public function addAvatar(Obj:MovieClip){
this.addChild(Obj);
}
}
}
Well ... if I may say so, this code looks quite wrong. Either something is missing from the code or this code will never make the bullets fly.
First off, you can set x and y of the new bullet directly (replace everything after "orientate this bullet from players body" with this):
tmpBulletId.x = Object(root).localSurvivor.x;
tmpBulletId.y = Object(root).localSurvivor.y;
Perhaps this already helps, but your code there should already do the same.
But to let these bullets fly into any direction, you also need to add an event listener, like so:
tmpBulletId.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e:Event) {
var movedBullet:MovieClip = MovieClip(e.currentTarget);
if (movedBullet.x < 0 || movedBullet.x > movedBullet.stage.width ||
movedBullet.y < 0 || movedBullet.y > movedBullet.stage.height) {
// remove move listener, because the bullet moved out of stage
movedBullet.removeEventListener(Event.ENTER_FRAME);
}
// remove the comment (the //) from the line that you need
MovieClip(e.currentTarget).x += 1; // move right
// MovieClip(e.currentTarget).y -= 1; // move up
// MovieClip(e.currentTarget).x -= 1; // move left
// MovieClip(e.currentTarget).y += 1; // move down
}
This example lets your bullet fly to the right. If you need it flying into another direction, just comment out the line with the "move right" comment and uncomment one of the other lines.
This is of course a very simple example, but it should get you started.
I hope this helps, and that my answer is not the wrong answer to the question.
As far as I have expirienced it you can have only one copy of MovieClip object added to specific child. Best approach is to use ByteArray for the clip source and instantiate new MovieClip and pass the ByteArray as a source. It have something to do with child/parent relation since a DisplayObject can have only one parent (and a way to detach the object from scene too).
Well i ended up writeing the whole code from scratch for a 3rd time and ran into a similar problem and just for reference to anybody else that comes to a problem thats random as this one i found that problem was likly does to a conversion error somewhere that doesn't necessarily break any compiling rules. Just that i was calling a movieclip and not the class it self.