How can I access the stage and especially the width and mouse position of the flash Movie from a custom class?
package classes
{
import flash.events.*;
import flash.display.*;
public class TableManager extends Sprite
{
public function TableManager() {
sayStage();
}
public function sayStage():void
{
trace(stage);
}
}
}
This will only return nill. I know that DisplayObjects don't have any stage until they have been initiated so you can't access the stage in your constructor but even if I call sayStage() later as an instance method it won't work.
What am I doing wrong?
You can pass a reference of the root movieclip (i.e. the stage) to your custom class.
e.g.
Then when instantiating your instance of TableManager from the root timeline:
stage
will be null as long as theSprite
hasn't been added to the display list - it's nothing to do with initiation. E.g.As @crooksy88 suggests, either pass in the stage to the constructor, or keep it as a static somewhere, say your main document class, so that you can access it everywhere.
If TableManager is on the stage you can access the stage with
this.stage
.The trick is you have to wait for the instance to be added to the stage. You can listen for the
ADDED_TO_STAGE
event so you know when that's happened.The most defensive way to write this is:
If the object is already on the stage at the time of initialization, then immediately call the
init
function with no arguments. If not wait until its been added to the stage. Then when theinit
function gets called, if it was called as the result of an event, then detach the event handler, and move along.here is a pretty good solution you only need to reference the stage inside your class you just pass it as a simple object, here how to do that
this is how you make instance to run it, i have used the constructor method but you can change it to any function as you wish and call it whenever you need it.
here is some few Examples how to access stage from class
https://stackoverflow.com/a/40691908/1640362
https://stackoverflow.com/a/40691325/1640362
i think usefull for You should be create static reference to stage :
in Your main class add line and set stage :
and than in custom class :