actionscript-3flixel

AS3/Flixel: "Access of possibly undefined property."


Pretty new flixel/AS3 user here, though not entirely new to coding. Anyways, the error is pretty straightforward in it's cause, but not it's solution.

"Error: Access of possibly undefined property through a reference with static type org.flixel:FlxSprite."

It gets thrown 6 times, twice with the property scrap.selected and four times with scrap.distanceToMouse - I've marked each line that throws an error with comments.

I've searched throughout the web and StackOverflow specifically. It looks like a pretty common problem, but I haven't been able to apply any solutions to my specific situation. Anyways, Here's the relevant code...

ScrapManager.as

    if (FlxG.mouse.pressed)
    {
        var ClosestDistance:int = 500; 
        for each (var scrap:FlxSprite in this)
        {
            scrap.selected = false; //error here!~ 
            var dx:int = scrap.x - FlxG.mouse.screenX;
            var dy:int = scrap.y - FlxG.mouse.screenY;
            scrap.distanceToMouse = (dx * dx) + (dy * dy); //error here!~

            if (scrap.distanceToMouse < ClosestDistance) //error here!~
            {
                ClosestDistance = scrap.distanceToMouse; //error here!~
            }
        }
        for each (var scrap:FlxSprite in this) 
        {
            if (scrap.distanceToMouse == ClosestDistance) //error here!~
            {
                scrap.selected = true; //error here!~
            }
        }
    }

Scrap.as

package 
{
    //import stuff...

    public class Scrap extends FlxExtendedSprite
        {
            public var selected:Boolean = false; 
            public var distanceToMouse:int; 
            //and more stuff...

I think (hope) that's all that's needed to solve this, but I'll be happy to provide more if needed. Thanks for reading. :D


Solution

  • for each (var scrap:FlxSprite in this)
    

    Are you certain that every property in "this" is an instance of FlxSprite? Maybe you need to store a collection of the FlxSprites inside ScrapManager and loop through those instead?

    I'd suggest tracing out "scrap" in those loops to make sure it is the right data type. If it is, and it is still giving out those errors, you should be able to narrow it down to the specific object that's giving you the problem.