【问题标题】:Get stage in ActionScript-3 without a DisplayObject?在没有 DisplayObject 的情况下在 ActionScript-3 中获得舞台?
【发布时间】:2014-01-31 09:08:27
【问题描述】:

我如何才能获得对我的舞台的引用没有已经添加到舞台的 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();
}

【问题讨论】:

  • 我认为您需要将其传递给您的班级。你的班级需要方法。

标签: actionscript-3 flash sprite stage


【解决方案1】:

舞台参考在您的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);就可以了。

【讨论】:

  • 是的,如果上述问题的答案是“在 AS-3 中不可能”,那就是这样。
  • 您不能从实用程序类自行初始化阶段引用,无论如何您都必须从以Main 开始的主代码执行线程调用该类的方法可以访问舞台的精灵/MC 实例。此外,如果您要处理静态变量/函数,将代码放在方法之外将不会编译(IIRC 我在这里看到了一个问题)。所以是的,一个独立类的“引导程序”来发现它的环境是“在 AS3 中不可能”。就是从外面接收这个信息。
  • 实际上它编译得很好“将代码放在方法之外不会编译”(请参阅我的编辑)除非你的意思是别的。
【解决方案2】:

您需要初始化 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2013-05-22
    • 1970-01-01
    • 2011-01-07
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多