繁体   English   中英

在没有DisplayObject的情况下进入ActionScript-3舞台?

[英]Get stage in ActionScript-3 without a DisplayObject?

如何在没有将Sprite / DisplayObject添加到舞台的情况下获得对舞台的引用?


更多信息:我有一个静态类,它是一个实用程序类,我希望它在静态类构造函数中初始化,但我还需要对该阶段的引用。

 public class UtilClass { trace("init: " + stage); } 

在AS-3应用程序中调用的第一件事是主Sprite / DisplayObject的构造函数,它可以访问舞台。 因此,该阶段存在。 然后,我调用UtilClass实用程序方法。 现在,我希望它可以在首次使用时自行进行初始化(当阶段已经存在时)。
我想知道舞台对象是否可以从任何地方访问而无需从实用程序类外部进行初始化。

编辑:

 public class SimpleSprite extends Sprite { public static var aaa:int = 12; public static function test():void { trace("here I am"); } trace(aaa, Capabilities.screenResolutionX+", "+Capabilities.screenResolutionY); test(); } 

根据平台的不同,可以在MainTimelineMain实例中使用该阶段引用。 您可以在此处添加代码,以在需要时将该引用传递给其他类。 该类应具有一个方法(在您的情况下为静态方法),该方法将接受一个Stage参数并将其存储在类内的某个位置。

public class UtilClass {
    private static var theStage:Stage=null;
    public static function initialize(s:Stage):void {
        if (theStage) return; // we're initialized already
        theStage=s;
    }
    // once you call this, you can "trace(theStage)" and get correct output
    // other methods can also rely on theStage now.
}

然后调用UtilClass.initialize(stage); 并且您被设置。

您将需要初始化UtilClass并通过阶段引用。 我建议您只为“管理”阶段参考提供一个类。

您可以尝试这样的事情(只是一个简单的例子):

public class StageReference
{
    public static const STAGE_DEFAULT:String = 'stageDefault';
    protected static var _stageMap:Dictionary;

    public static function getStage(id:String = StageReference.STAGE_DEFAULT):Stage
    {
        if (!(id in StageReference._getMap()))
            throw new Error('Cannot get Stage ("' + id + '") before it has been set.');

        return StageReference._getMap()[id];
    }

    public static function setStage(stage:Stage, id:String = StageReference.STAGE_DEFAULT):void
    {
        StageReference._getMap()[id] = stage;
    }

    public static function removeStage(id:String = StageReference.STAGE_DEFAULT):Boolean
    {
        if (!(id in StageReference._getMap()))
            return false;

        StageReference.setStage(null, id);

        return true;
    }

    protected static function _getMap():Dictionary
    {
        if (!StageReference._stageMap) StageReference._stageMap = new Dictionary();

        return StageReference._stageMap;
    }
}

启动应用程序时(主类或开始包含逻辑的位置)

  StageReference.setStage(stage);

而当您需要获得阶段参考时

  trace('Checking the Stage: ', StageReference.getStage());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM