0

我有两节课。一个叫“ Commands”,一个叫“ ZombieWave”。我有一个ZombieWave名为“ initiateZombieWave”的函数。这是功能:

public void functionWait() {
    TimerManager.getInstance().schedule(new Runnable() {
        public void run() {
            player.message("test works")
        }
    }, 3000);
}

该函数使用一个调用类TimerManager来安排一个新实例在 3 秒(3,000 毫秒)后执行某个代码。

当我试图functionWait通过类使用该功能时Commands,我必须使用:

new ZombieWave().functionWait();

我不确定这是从另一个类访问外部函数的正确方法,是吗?好吧,对于我的问题。但是TimerManager,不起作用。我不太确定为什么。

这是该TimerManager课程的链接。该函数的用法是正确的,因为当我尝试从Commands类中使用它时,它可以工作。ZombieWave那么,当我尝试在课堂上使用它时,为什么它不起作用呢?(functionWaitis not only TimerManager,我只是放了TimerManager代码。其他代码无所谓)。

4

2 回答 2

0

You need a new ZombieWave object because you're using an instance member in your functionWait() (player).

If you call this function from a ZombieWave instance, you don't need to create a new ZombieWave instance. this.functionWait() is enough (since this is already a ZombieWave instance).

If you make this function static, you do not longer need a new ZombieWave instance, but you cannot use player since it's an instance member of ZombieWave. You can pass this player to the static method though. Here's an example:

   public static void functionWait(final Player player) {
       TimerManager.getInstance().schedule(new Runnable() {
           public void run() {
               player.message("test works")
           }
       }, 3000);
   }

   // Call it
   ZombieWave.functionWait(player);

Another way of doing this is to make a singleton class, as hinted by Dukeling, but this means you can only have one ZombieWave instance at any given time. if this is not a restriction then you might consider the singleton pattern.

于 2013-07-04T14:22:36.677 回答
0

尝试这个:

public void functionWait() {
       TimerManager.getInstance().schedule(new Runnable() {
           public void run() {
               ZombieWave.this.player.message("test works")
           }
       }, 3000);
   }
于 2013-07-04T14:20:41.097 回答