2011-12-13 103 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

相关问题