迭代libGDX中的组

时间:2017-03-14 00:42:09

标签: java android loops libgdx scene2d

是否有更简单,更清晰的方法来迭代libGDX中的Group成员?

stage.addActor(group);
for (Actor actor : group.getChildren()) {
  ((GroupActor) actor).method() // this gets really messy for large loops
  GroupActor groupActor = (GroupActor) actor;
  groupActor.method(); // possible, but seems redundant
}

当我知道时,是否有更好的方法,所有组成员都属于Groupactor类?像这样的东西会很好(但不起作用):

for ( Actor actor : (GroupActor) group.getChildren())
for ( (GroupActor) Actor actor : group.getChildren())

1 个答案:

答案 0 :(得分:0)

Group group=new Group();
SnapshotArray<Actor> actors=group.getChildren();

SnapShotArray通过它的父级实现Iterable接口,因此我们可以为每个循环使用它。

for (Actor actor:actors) {

        // In this you're not keeping reference of your GroupActor just you downcast and run method of GroupActor
        ((GroupActor)actor).method();

        // You downcast to GroupActor, keep reference and then run method of GroupActor
        GroupActor groupActor=  (GroupActor) actor;
        groupActor.method();
}

你无法向SnapShotArray转发GroupActor(演员),Inconvertible type

for (Actor actor:(GroupActor)actors){
}

内部会发生什么:

for(Iterator<Actor> i = actors.iterator(); i.hasNext(); ) {
    Actor item = i.next();
    System.out.println(item);
}

所以按照你的第一种方式去吧:)