2014-01-31 75 views
1

如何獲得對我的舞臺的引用,而不是的Sprite/DisplayObject已添加到舞臺上? 在沒有DisplayObject的情況下在ActionScript-3中獲取舞臺?


更多信息:我有一個靜態類,它是一個工具類,我希望它在靜態類構造函數中初始化,但我也需要對該階段的引用。那個叫我的AS-3的應用程序

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

的第一件事是我的主要雪碧/ DisplayObject的構造,它可以訪問舞臺。所以舞臺就存在於這一點上。 然後我打電話給我的實用方法UtilClass。現在我想讓它在第一次使用時自動初始化(當舞臺已經存在時)。
我想知道是否可以從任何地方訪問stage對象,而無需從實用程序類的外部初始化。

編輯:

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(); 
} 
+0

你需要把它傳遞給你的班級,我認爲。你的課程需要方法。 – putvande

回答

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);然後你就設定了。

+0

是的,如果對上述問題的答案是**「在AS-3中不可能」**,那麼這就是要走的路。 – Bitterblue

+0

您無法從實用程序類*本身*初始化階段引用,您無論如何都必須從具有訪問階段的「Main」精靈/ MC實例中啓動的主代碼執行線程中調用該類的方法。另外,如果你要解決靜態變量/函數(IIRC,我在這裏看到一個問題,請求這個),那麼把代碼放在方法外部就不會編譯。所以是的,獨立類的「引導」來發現它的環境是「**在AS3 **中不可能的」。它是從外部接收這些信息。 – Vesper

+0

實際上它編譯得很好_「把代碼放在方法之外不會編譯」_(請參閱我的編輯),除非你的意思是別的。 – Bitterblue

0

您將需要初始化您的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()); 
相關問題