Strange object property issue in flash - actionscript-3

I've struck a rather odd problem in my flash game. I get a "Error #1009: Cannot access a property or method of a null object reference." error in the following block of code:
public function createHero()
{
hero = new Object();
hero.mc = gamelevel.hero;
hero.dx = 0.0;
hero.dy = 0.0;
hero.inAir = false;
hero.direction = 1;
hero.animstate = "stand";
hero.walkAnimation = new Array(2, 3, 4, 5, 6, 7, 8);
hero.animstep = 2;
hero.jump = false;
hero.moveLeft = false;
hero.moveRight = false;
hero.jumpSpeed = 0.8;
hero.walkSpeed = 0.15;
hero.width = 64.0;
hero.height = 96.0;
hero.startX = hero.mc.x;
hero.startY = hero.mc.y;
hero.profile = "technology";
hero.ability = "robot";
hero.activePhotoFrame = false;
}
Using the debugger I've narrowed the error down to "hero.mc = gamelevel.hero;". I tried figuring out if hero.mc or gamelevel.hero was the culprit by using a test object.
testObject = gamelevel; //worked perfectly fine
testObject = gamelevel.hero; //gave the error
testObject.mc = gamelevel; //also gave the error
testObject.mc = gamelevel.hero; //gave the same error as well
I don't understand what the problem is.
For clarification "gamelevel" is the instance name of a movieclip containing another movieclip with the instance name "hero"
The problem isn't limited to the hero object. If I comment it out I get the error with any other object assigning gamelevel.something to a mc property.
What makes it stranger is that this worked perfectly fine before.
If any other information is required, please don't hesitate to ask.

gotta be on stage before you can access stage instances.
this.addEventListener(Event.ADDED_TO_STAGE,createHero)

Turned out one of the images was corrupted...

Related

Adding a dynamically created DataGrid as child or element does not work

I am trying to develop an application in AS3. What I am really trying to achieve is to have only one datagrid and having it show, you say, three different set of datas. (the real count will be changing dynamically, and it does not matter as the problem is not relevant with this) Yes, it has to be only one datagrid because of you know, I need a compact interface.
The class "Sonuc" has three properties which are string versions of inputs from constructor. A typical "Sonuc" object is something like this.
var sonuc1:Sonuc = new Sonuc(1,1,false);
//sonuc1.num = "1"
//sonuc1.type = "1"
//sonuc1.isTrue = "No"
The reason that I have informed you about "Sonuc" class is that I wanted you to know that class was not something too complicated. And x.mxml is the test mxml where I only load the class for testing purposes.
This is what I have coded so far
public class ResultInterface extends UIComponent
{
private const desiredWidth:int = 250;
private const desiredHeight:int = 150;
private const sonuc1:Sonuc = new Sonuc(1,1,false);
public var tablo:DataGrid = new DataGrid();
public var kolonArray:Array = new Array ();
public var sonucArray:Array = new Array ();
public var currentIndex:int = new int ();
public var prevButon:Button = new Button();
public var nextButon:Button = new Button();
public function ResultInterface():void
{
currentIndex = 0;
super();
tablo = new DataGrid();
width=desiredWidth+40;
height=desiredHeight+60;
this.tablo.width = desiredWidth;
this.tablo.height = desiredHeight;
this.tablo.x = 20;
this.tablo.y = 40;
prevButon.x = 10;
prevButon.y = genislik/2 - 10;
prevButon.width =
prevButon.height = 10;
nextButon.x = genislik +20;
nextButon.y = genislik/2 -10;
nextButon.width =
nextButon.height = 10;
var referansColl:ArrayCollection = new ArrayCollection();
sonucArray.push(referansColl);
tablo.dataProvider = sonucArray[currentIndex];
var sampleCol:DataGridColumn = new DataGridColumn();
sampleCol.dataField = "num";
sampleCol.headerText = "Number";
var sampleCol2:DataGridColumn = new DataGridColumn();
sampleCol2.dataField = "type";
sampleCol2.headerText = "Type";
var sampleCol3:DataGridColumn = new DataGridColumn();
sampleCol3.dataField = "isTrue";
sampleCol3.headerText = "Is it true?";
kolonArray.push(sampleCol,sampleCol2,sampleCol3);
tablo.columns = kolonArray;
this.addElement(tablo); //**** this is the problematic line
this.addChild(oncekiButon);
this.addChild(sonrakiButon);
}
public function getNewSonuc(incoming:Sonuc):void
{
sonucArray[currentIndex].addItem(incoming);
}
public function newTablo():void
{
var newTablo:ArrayCollection = new ArrayCollection();
currentIndex = sonucArray.push(newTablo);
}
public function prev(evt:Event):void //I haven't written event listeners yet
{
if(currentIndex > 0)
currentIndex--;
nextButon.enabled = true;
if(currentIndex == 0)
prevButon.enabled = false;
}
public function birSonrakine(evt:Event):void
{
if(currentIndex < sonucArray.length)
currentIndex++;
prevButon.enabled = true;
if(currentIndex == sonucArray.length)
nextButon.enabled = false;
}
in this version, I get a syntax error "call to a possibly undefined method addElement"
I also tried having the base class as "Sprite" and "Canvas"
when I used addChild instead of addElement, then I get runtime error "addChild is not available to this class"
when I just commented the problematic line out, everything was loaded perfectly but the datagrid itself.
Note that error occurs before sending in some data (Sonuc) to datagrid.
and when I tried with canvas and with addelement, I get "Cannot access a property or method of a null object reference" with some weird functions and classes and packages.
1009: Cannot access a property or method of a null object reference.
at mx.styles::StyleProtoChain$/initProtoChainForUIComponentStyleName()[E:\dev\4.y\frameworks\projects\framework\src\mx\styles\StyleProtoChain.as:358]
at mx.styles::StyleProtoChain$/initProtoChain()[E:\dev\4.y\frameworks\projects\framework\src\mx\styles\StyleProtoChain.as:171]
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::initProtoChain()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:10926]
at mx.core::UIComponent/regenerateStyleCache()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:10989]
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::addingChild()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7465]
at mx.core::UIComponent/addChild()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7162]
at mx.controls.listClasses::ListBase/createChildren()[E:\dev\4.y\frameworks\projects\mx\src\mx\controls\listClasses\ListBase.as:3772]
at mx.controls::DataGrid/createChildren()[E:\dev\4.y\frameworks\projects\mx\src\mx\controls\DataGrid.as:1143]
at mx.core::UIComponent/initialize()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7634]
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::childAdded()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7495]
at mx.core::Container/http://www.adobe.com/2006/flex/mx/internal::childAdded()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:3974]
at mx.core::Container/addChildAt()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:2618]
at mx.core::Container/addChild()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:2534]
at mx.core::Container/addElement()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:2981]
at genel.siniflar::ResultInterfaceArayuz()[C:\Users\Ege\Adobe Flash Builder\brainswift2\src\genel\siniflar\ResultInterface.as:95]
at x()[C:\Users\Ege\Adobe Flash Builder\brainswift2\src\x.mxml:27]
at _x_mx_managers_SystemManager/create()[_x_mx_managers_SystemManager.as:54]
at mx.managers.systemClasses::ChildManager/initializeTopLevelWindow()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\systemClasses\ChildManager.as:311]
at mx.managers::SystemManager/initializeTopLevelWindow()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:3057]
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::kickOff()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:2843]
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::preloader_completeHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:2723]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\preloaders\Preloader.as:542]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
I really need your help folks, please answer as soon as possible.
Well, I tried calling "addElement" from outside of the constructor, and it worked. However I don't know what did exactly cause this error and I know that my solution is not a legitimate one. And I would like to learn proper solution to this problem.
changes to resultInterface.as
// this.addElement(tablo); **** this is the problematic line, we have commented it out
this.addChild(oncekiButon);
this.addChild(sonrakiButon);
changes to x.mxml
public function onCreationComplete(evt:Event):void
{
showResult.addElement(showResult.tablo);
addElement(showResult);
}

Make an item glow when the player is walking

I'm making a game (point & click) and I'm trying to make the usable item glow when the player is walking. It’s quite simple but I don’t why I fail. I must have missed something.
I have already the code as my usable item is glowing when I'm putting it on an other usable item. So I've got a Engine class where I'm trying to put the code that make the item glow when the player is walking. And a DraggedItem Class. This class allows the user to drag inventory items over the stage.
In my DraggedItem class I've got this function :
private function itemGlow(isGlowing:Boolean):void{
if (isGlowing){
var glow:GlowFilter = new GlowFilter();
glow.color = 0xFFFF00;
glow.alpha = .75;
glow.blurX = 10;
glow.blurY = 10;
glow.quality = BitmapFilterQuality.MEDIUM;
draggedItem.filters = [glow];
} else {
draggedItem.filters = null;
}
}
In my Engine class I'd like to use this function when my player is walking.
I tought I could put something like this :
back = new Background(stage, thisBack);
back.currentBack.ground.addEventListener(MouseEvent.MOUSE_DOWN, shineItems, false, 0, true);
private function shineItems(e:MouseEvent):void{
trace(shineItems);
var thisClip = usableItems
if (playerControl){
stage.dispatchEvent(new Event("playerMoving"));
draggedItem.itemGlow(true);
}
}
But it's not it.
I've must import the function in the wrong way.
So I've try to add in the Engine Class and change draggedItem.itemGlow; by itemGlow;.
private function itemGlow(isGlowing:Boolean):void{
if (isGlowing){
var glow:GlowFilter = new GlowFilter();
var thisClip = usableItems
glow.color = 0xFFFF00;
glow.alpha = .75;
glow.blurX = 10;
glow.blurY = 10;
glow.quality = BitmapFilterQuality.MEDIUM;
thisClip.filters = [glow];
} else {
thisClip.filters = null;
}
}
But it's not working either.
Any idea ?
EDIT
I've put draggedItem.itemGlow(true); in the shineItems function and I've got this error now :
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.laserdragonuniversity.alpaca::Engine/shineItems()[C:\Users\stephanberger4\Desktop\07 novembre\Tactile\com\laserdragonuniversity\alpaca\Engine.as:321]
line 321 is : draggedItem.itemGlow(true);
If it's an instance of the DraggedItem class that you want to glow, you can set a DraggedItem instance's filters (from within the class) like this:
filters = [glow];
or:
this.filters = [glow];
This assumes DraggedItem extends DisplayObject, to access the filters property.
Also, in the shineItems function, you refer to itemGlow as a property when it is a function; it should be:
draggedItem.itemGlow(true);
or
draggedItem.itemGlow(false);

Feathers (Starling-based Adobe AIR library) List control doesn't work the second time it's instantiated

I'm having a problem with a Feathers List control. It works the first time I enter the screen that contains the list, but the second time I enter that screen in the same app execution, the scrolling list doesn't scroll at all plus texts don't appear. No error appears in the console.
I've tried lots of stuff, but I still have the same problem: It only works the first time it's instantiated. If I exit the screen and come back, it doesn't work at all!
When exiting the screen it's disposed and when coming back to that screen it's a new instance of List. Why does it work only the first time?
Also, I tried not using a custom ItemRenderer at all, so only the images appear, no text, and still the same happens. The list doesn't respond to scroll events the SECOND time is instantiated. So it's not a problem with the ItemRenderer.
Ok, here's some code:
typeList = new List();
typeList.x = Settings.appResolution[0] - Settings.menuTypeColumnWidth;
typeList.y = Settings.topBarHeight;
typeList.width = Settings.menuTypeColumnWidth;
typeList.height = Settings.appResolution[1] - Settings.topBarHeight;
typeList.dataProvider = new ListCollection(listContents);
typeList.itemRendererProperties['labelField'] = 'text';
typeList.itemRendererProperties['accessoryLabelField'] = 'articles';
typeList.itemRendererProperties['iconSourceField'] = 'thumbnail';
var listLayout:VerticalLayout = new VerticalLayout();
listLayout.gap = Settings.menuTypeItemGap;
typeList.layout = listLayout;
typeList.addEventListener(Event.CHANGE, onListChange);
typeList.itemRendererType = MenuTypeItemRenderer;
As you can see it's nothing out of the ordinary.
Thanks for your help.
Are you sure that the ListCollection used by the list is still available when the 2nd instantiation is performed?
_list.dataProvider = new ListCollection(items);
Here's a sample of code I've used. See if it offers any clues. I call the clearList function before the class is removed from the stage.
private function onAddedToStage(e:starling.events.Event):void {
removeEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
addEventListener(starling.events.Event.REMOVED_FROM_STAGE, onRemovedFromStage);
//only do this if a list does not already exist.
if(!_list){
items = new <ListItem>[];
for(var i:int = 0; i < 20; i++) {
items.push(new ListItem("Item text"));
}
_list = new List();
_list.itemRendererFactory = function():IListItemRenderer {
renderer = new ListItemRenderer();
// pass your skins in here
renderer.defaultSkin = new Image(AssetManager.getAtlas().getTexture("listItemClear_normal"));
renderer.defaultSelectedSkin = new Image(AssetManager.getAtlas().getTexture("listItemClear_selected"));
return renderer;
};
vl = new VerticalLayout();
vl.hasVariableItemDimensions = false;
_list.layout = vl;
_list.scrollerProperties.snapScrollPositionsToPixels = true;
_list.scrollerProperties.verticalScrollPolicy = Scroller.SCROLL_POLICY_AUTO;
_list.scrollerProperties.horizontalScrollPolicy = Scroller.SCROLL_POLICY_OFF;
_list.scrollerProperties.scrollBarDisplayMode = Scroller.SCROLL_BAR_DISPLAY_MODE_FLOAT;
//need to use a factory as we are not using a theme
_list.scrollerProperties.verticalScrollBarFactory = myScrollBarFactoryFunction;
_list.isSelectable = false;
_list.scrollerProperties.hasElasticEdges = true;
_list.itemRendererProperties.height = 60r;
_list.addEventListener(starling.events.Event.CHANGE, list_changeHandler);
_list.width = 320;
_list.height = StartUp._stageHeight;
addChild(_list);
_list.dataProvider = new ListCollection(items);
}
}
public function myScrollBarFactoryFunction():IScrollBar {
scrollBar = new SimpleScrollBar();
scrollBar.direction = SimpleScrollBar.DIRECTION_VERTICAL;
scrollBar.thumbProperties.defaultSkin = new Scale3Image(new Scale3Textures(AssetManager.getAtlas().getTexture("vertical-scroll-bar-thumb-skin"), 5, 14, Scale3Textures.DIRECTION_VERTICAL));
scrollBar.thumbProperties.width = 4;
scrollBar.thumbProperties.minHeight = 20;
scrollBar.width = 4;
return scrollBar;
}
public function clearList():void {
if (_list) {
scrollBar = null;
renderer = null;
vl = null;
removeChild(_list);
_list = null;
items.length = 0;
items = null;
}
}

Error 1009 cannot access a property----again

Hello I'm stuck on this one which is trying to show a game level on the game and getting an output error 1009. I'm doing something wrong but can't figure. Here is the code:
if ( levelNumber ==1) {
var level:Number = 1;
showLevel.text=level.toString();
showLevel.text = String ("Level: " +level);
if ( levelNumber ==2) {
var level:Number = 2;
showLevel.text=level.toString();
showLevel.text = String("Level: " +level);
var numBombs:Number = 4;
}else if( levelNumber ==3 ) {
var level:Number = 3;
showLevel.text=level.toString();
showLevel.text = String ("Level: " +level);
The debugger says it's the line with showLevel.text=level.toString(); which I have set as a Number ie private var level:Number =0. I hope this is sufficient code to let you know what's going on here. It's also coming up with a duplicate variable definition - compiler error on var level:Number =2 and the next one that =3.Thanking you in advance for any assistance. Cheers.
Error #1009 is indeed a null reference error. I see your level is declared and has a right value.
Maybe the point is that your showLevel object (I guess it's a label) is not declared yet.
The problem can be that you use:
private var showLevel:mx.controls.Label;
instead of:
private var showLevel:mx.controls.Label = new mx.controls.Label();
otherwise if you make your showLevel in a viewStack you must be sure that your content is created yet. Therefor you can use:
<mx:ViewStack id="yourView" creationPolicy="all">

Unloading a Loader with actionscript 3

Hello and thank you very much for looking at this. I've spent too many hours struggling.
The code below loads a slideshow of four images, along with thumbnails for those images. It works fine.
I've added a button called "invis_button", that when pressed is supposed to remove the 3 loaders that make up the slideshow, using the removeChild command for each loader.
But this is the problem, there are 3 loaders involved in the slide-show. The removeChild command successfully removes one of the loaders (named "loader3"), but not the other two ("container3", and "thumbLoader3"). It returns an error stating "access of undefined property thumbLoader3" or "Container3".
Can someone tell me why this is ? Or better still, how to make that button (invis_button) unload the entire slide-show.
var images3:Array = ["ad_bona1.jpg", "ad_bona2.jpg", "ad_darkhawk1.jpg", "ad_darkhawk2.jpg"];
var thumbX3:Number = -375;
var thumbY3:Number = 220;
var loader3:Loader = new Loader();
loader3.load(new URLRequest("assets/ad_bona1.jpg"));
addChild(loader3);
loader3.alpha = 0;
loadThumbs3();
function loadThumbs3():void
{
var thumbLoader3:Loader;
var container3:Sprite = new Sprite();
addChild(container3);
container3.buttonMode = true;
for(var i3:uint = 0; i3 < images3.length; i3++)
{
thumbLoader3 = new Loader();
thumbLoader3.load(new URLRequest("assets/thumbs/" + images3[i3]));
thumbLoader3.x = thumbX3;
thumbLoader3.y = thumbY3;
thumbX3 += 85;
container3.addChild(thumbLoader3);
thumbLoader3.addEventListener(MouseEvent.CLICK, thumbClicked3);
}
}
function thumbClicked3(event:MouseEvent):void
{
var path3:String = event.currentTarget.contentLoaderInfo.url;
path3 = path3.substr(path3.lastIndexOf("/") + 1);
loader3.load(new URLRequest("assets/" + path3));
}
///PROBLEM BELOW, button removes only "loader3" and not the other two for some reason
invis_button.addEventListener(MouseEvent.CLICK, unload_loaders);
function unload_loaders(event:MouseEvent):void{
removeChild(loader3);
removeChild(thumbLoader3);
removeChild(container3);
}
Not sure if this is the entire reason behind what you're observing... but for starters, "thumbloader3" and "container3" are scoped locally to the loadThumbs3() method, which means once you finish executing the function, Flash's handles to those objects are lost (not to mention being in an entirely different scope)... try creating class-level properties for those two. Once that's done you should be able to successfully remove them from the stage later on.
I hope that you're also properly destroying your objects, and for the sake of brevity you just chose to omit that code above.
I've edited the code you had above & put the properties into the proper scope. (the multiple copies of thumbLoader3 are now collected inside of a vector (specialized array) so that they can be properly addressed when it comes time to destroy them)
I also wrote you a proper destroy method. ;)
I haven't tried it on my own machine, but give it a spin & see how it goes.
var images3:Array = ["ad_bona1.jpg", "ad_bona2.jpg", "ad_darkhawk1.jpg", "ad_darkhawk2.jpg"];
var thumbX3:Number = -375;
var thumbY3:Number = 220;
// begin new instance properties..
// created a new property, allowing you to group (and hold on to) the multiple thumbLoaders
var thumbLoader3Vector:Vector.<Loader> = new Vector.<Loader>();
var container3:Sprite;
// end new instance properties
var loader3:Loader = new Loader();
loader3.load(new URLRequest("assets/ad_bona1.jpg"));
addChild(loader3);
loader3.alpha = 0;
loadThumbs3();
function loadThumbs3():void
{
// this is where container3 used to be declared
container3 = new Sprite();
addChild(container3);
container3.buttonMode = true;
for(var i3:uint = 0; i3 < images3.length; i3++)
{
var tPtr:int = thumbLoader3Vector.length;
thumbLoader3Vector.push(new Loader());
// this is where thumbLoader3 used to be declared & instantiated
thumbLoader3Vector[tPtr].load(new URLRequest("assets/thumbs/" + images3[i3]));
thumbLoader3Vector[tPtr].x = thumbX3;
thumbLoader3Vector[tPtr].y = thumbY3;
thumbX3 += 85;
container3.addChild(thumbLoader3Vector[tPtr]);
thumbLoader3Vector[tPtr].addEventListener(MouseEvent.CLICK, thumbClicked3);
}
}
function thumbClicked3(event:MouseEvent):void
{
var path3:String = event.currentTarget.contentLoaderInfo.url;
path3 = path3.substr(path3.lastIndexOf("/") + 1);
loader3.load(new URLRequest("assets/" + path3));
}
///PROBLEM BELOW, button removes only "loader3" and not the other two for some reason
invis_button.addEventListener(MouseEvent.CLICK, unload_loaders);
function unload_loaders(event:MouseEvent):void{
// since the thumbLoader3 Loaders are children of container3 in the display list, we need to remove them first
for(var $i:uint = 0;$i<thumbLoader3Vector.length;$i++)
{
removeChild(thumbLoader3Vector[$i]);
// also make sure you remove the listener, so that the object will be picked up by garbage collection
thumbLoader3Vector[$i].removeEventListener(MouseEvent.CLICK, thumbClicked3);
}
// and then just set the entire vector to null
thumbLoader3Vector = null;
// remove the loader3 object & set it to null
removeChild(loader3);
loader3 = null;
// remove the container3 object & set it to null
removeChild(container3);
container3 = null;
}