Question

If there is a main class which uses class Chan, given two codes, for example

public class Chan extends Sprite
{

    public function Chan():void
    {
       this.graphics.beginFill(0x123456); 
       this.graphics.drawRect(100,100,30,30);
    }
}

And

public class Chan extends Sprite
{
    public static var rect:Sprite=new Sprite(); 
    public function Chan():void
    {
       rect.graphics.beginFill(0x123456); 
       rect.graphics.drawRect(100,100,30,30);
    }
}

Why does one seems to work, and the other doesn't ?

Was it helpful?

Solution

scope. In the first example, you are drawing on the sprite instance itself that is already on the stage. rect in your second example is static and belongs to the class. So although you are drawing in it, it is not visible... it's only in memory. If you add one more line to the second example, it will also be visible.

public class Chan extends Sprite
{
    public static var rect:Sprite=new Sprite(); 
    public function Chan():void
    {
        rect.graphics.beginFill(0x123456); 
        rect.graphics.drawRect(100,100,30,30);
        this.addChild(rect);
    }
}

EDIT:

I wanted to elaborate on this a bit. The fact that rect was a static var wasn't the main problem. I mentioned it was static in my answer but didn't want that to confuse you. The reason it doesn't work is the scope where you were drawing wasn't in view... it was simply a variable. so even if it said:

public var rect:Sprite = new Sprite();

It would not be visible until you called addChild(rect) to actually add it into view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top