Why is the stage undefined in my ActionScript 3 class even though I imported the Stage class?

 package    {

 import flash.display.Stage;

 public class MyGlobal {

  public static  var CX:Number = stage.stageWidth / 2;
  public static  var CY:Number = stage.stageHeight / 2;  

 }

}

Error "1120: Access of undefined property stage."WHY?

+3
source share
4 answers

As already mentioned, stage is a property of classes that inherit from DisplayObject. The stage is not available to the class until it is added to the scene, usually using the addChild method for DisplayObjectContainer.

+9
source

stage , . DisplayObject, stage . DisplayObject, addChild() .

, , .

DisplayObject, , :

addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);

onAddedToStage() (EDIT: stage , ).

+3

, Object . , , , .

, :

public function Ball(b:Object,stageRef:Object)
{
    ballObject = b;
    speed = 10;
    stageRef.addEventListener(KeyboardEvent.KEY_DOWN,function(e:KeyboardEvent):void{
        currentKeyCode = e.keyCode; 
    });
    stageRef.addEventListener(KeyboardEvent.KEY_UP,function(e:KeyboardEvent):void{
        currentKeyCode = 0;   
    });
}
+1

Sam's answer is actually quite right. The easiest way to explain is that it stageis an instance, not a member of a class.

If your fields were not declared static, you can access the scene. But you will probably get a null-reference error;)

0
source

Source: https://habr.com/ru/post/1728138/


All Articles