2011-12-13 100 views
-1

我正在編寫一個小型Flash遊戲,並且不想訪問類之間的不同功能。在C#中,我習慣於將其設爲靜態,但我遇到了一些問題。AS 3.0中的公共靜態函數

這裏所說:

Main.as

package 
{ 
import Bus; 
    import flash.display.Sprite; 
import flash.events.Event; 
import flash.display.Stage; 

public class Main extends Sprite 
{ 
    public function Main() 
    { 
     addBus(); 
    } 
} 
} 

Bus.as

package 
{ 
import flash.display.Sprite; 
import flash.events.Event; 
import flash.display.Stage; 

public class Bus extends Sprite 
{ 
    public function Bus() 
    { 
    } 

    private static function addBus() 
    { 
     var bus:Bus = new Bus(); 

     bus.x = stage.stageWidth/2; 
     bus.y = stage.stageHeight/2; 

     addChild(bus); 
    } 
} 
} 

爲什麼我不能這樣做呢?

+0

您錯過了Bus.addBus(),嘖嘖嘖嘖 – Ryan 2011-12-15 09:51:29

回答

0

Bus類中的靜態函數被設置爲private。如果你公開,它應該工作得很好。

編輯:我不認爲這是你正在尋找的答案。你的靜態函數對它所在類的實例一無所知。你不能在一個靜態函數中調用addChild(),因爲它不知道分配給它的內容。您需要將Main類或Stage的實例傳遞給addBus函數。

例如:

public static function addBus(mainObj) { 
    //do your stuff here 
    mainObj.addChild(bus); 
} 

然後你的main函數將調用addBus(本)

0

此外,我相信你需要添加Bus.addBus()到您的主要功能,但它已經有一段時間,因爲我已經做了AS3編程

1

你有幾個問題。 首先:要調用靜態方法,您必須參考該類。

Bus.addBus(); 

這使得閃存知道你指的是總線類的靜態方法,而不是所謂的「addBus()」方法的主類。

其次,在你的Bus.addBus()方法中,你引用了非靜態變量。這可能會導致問題。尤其是,您引用了舞臺對象,因爲沒有靜態舞臺,舞臺對象將爲空。相反,您需要傳遞對舞臺的引用,或者您可以從該函數返回一個新的總線,並讓調用類以適當的方式將它添加到顯示列表中。

我會推薦第二種方法。

另外,您可能會對addBus()靜態方法有進一步的計劃。但我想指出,您可以通過如下構造函數輕鬆完成該功能:

package 
{ 
import flash.display.Sprite; 
import flash.events.Event; 
import flash.display.Stage; 

public class Bus extends Sprite 
{ 
    public function Bus(stageReference:Stage) 
    { 

     this.x = stageReference.stageWidth/2; 
     this.y = stageReference.stageHeight/2; 

     stageReference.addChild(bus); // This is kind of bad form. Better to let the parent do the adding. 
    } 
} 
} 

========================= ============================

編輯迴應評論

在ActionScript中,靜態方法是例外,不是規則。因此,要創建一個總線,您可以按照以下方式更改代碼。評論解釋了代碼。

package 
{ 
import Bus; 
import flash.display.Sprite; 
import flash.events.Event; 
import flash.display.Stage; 

public class Main extends Sprite 
{ 
    public function Main() 
    { 
     // Add a new member variable to the Main class. 
     var bus:Bus = new Bus(); 
     // we can call methods of our Bus object. 
     // This imaginary method would tell the bus to drive for 100 pixels. 
     bus.drive(100); 
     // We would add the bus to the display list here 
     this.addChild(bus); 
     // Assuming we have access to the stage we position the bus at the center. 
     if(stage != null){ 
       bus.x = stage.stageWidth/2; 
       bus.y = stage.stageHeight/2; 
     } 
    } 
} 
} 

這就是你如何創建你的類的實例並訪問它,而不需要任何靜態方法。「new」關鍵字實際上是調用類的構造函數方法的快捷方式,它返回該類的新實例。調用「new」的父項將該實例作爲子項並有權調用其所有公共方法和屬性。

+0

我不確定如何調用Main.as中的函數。你會然後做Bus.addBus(?)。此外,我不能訪問該功能,如果我不使它靜態?主要思想是我可以在Bus.as中完成整個功能,然後在Main.as中調用它(Bus.addBus();) – 2011-12-14 08:36:34

相關問題