2014-01-18 49 views
4

如何在libgdx中按名称获取演员?在libgdx中按名称获取演员

目前,我有以下的ChangeListener:

ChangeListener colorPickerListener = new ChangeListener() 
    { 
     public void changed(ChangeEvent event, Actor actor) 
     { 
      //Popup Window 
      toolboxStage.addActor(blockWindow); 
      //toolboxStage.getRoot().removeActor(blockWindow); 
      Gdx.app.log("LevelEditorScreen", "Color Picker Selected"); 
      Gdx.app.log("LevelEditorScreen", "HUD Width: " + HUD_WIDTH); 

      Gdx.input.setInputProcessor(toolboxStage); 
     } 
    }; 

演员是上面已经触碰演员。一旦这个特殊的演员被触动,我需要改变另一个演员的颜色。我究竟如何才能通过名字获得这位演员?

回答

3

首先,你需要为你的演员设置一个名称:(Actor#setName

myactor.setName("myactor"); 

然后你就可以得到所有的演员在舞台这是,这样的:(Stage#getActors

Array<Actor> stageActors = mystage.getActors(); 

然后,您可以用Actor#getName检查所有演员的那个名字:

int len = stageActors.size; 
for(i=0; i<len; i++){ 
    Actor a = stageActors.get(i); 
    if(a.getName().equals("myactor")){ 
     //a is your Actor! 
     break; 
    } 
} 

但是,如果您保留对所有Actor的引用并改为使用它,它将更容易更高性能

15

我想指出,已经有一种方法可以按名称找到Actor

它的工作原理是这样的:stage.getRoot().findActor(name)

不需要自己实现它。 :)

+1

每当我忘记这一点,并记住正确的搜索条件再次找到这个问题,我很难过,这没有标记为答案。谢谢! –

1

我会重新使用本集团的已知功能。每个阶段都有一个根组,这实现了通过名称查找演员。在使用分组系统的情况下,它的代码比答案中给出的代码更安全。

该组的代码看起来像这样,并且更安全,因为如果您将组添加到舞台上,它也会在组内查找。

/** Returns the first actor found with the specified name. Note this recursively compares the name of every actor in the group. */ 
    public Actor findActor (String name) { 
      Array<Actor> children = this.children; 
      for (int i = 0, n = children.size; i < n; i++) 
        if (name.equals(children.get(i).getName())) return children.get(i); 
      for (int i = 0, n = children.size; i < n; i++) { 
        Actor child = children.get(i); 
        if (child instanceof Group) { 
          Actor actor = ((Group)child).findActor(name); 
          if (actor != null) return actor; 
        } 
      } 
      return null; 
    } 

Link to Group Class

如果你需要搜索很多的时间来保存演员的refrence。如果不是只使用serch方法。

+1

我不认为它更安全,因为'stage.getActors()'还应该包含* all * actors。遍历该列表甚至可能更具性能。但我仍然会使用现有的API。我只是没有看到你的答案对于之前已经给出的两个答案有什么价值。 – noone