首先我实例化一个游戏状态

class GameState extends state{
ArrayList<Level> levels;
int currentLevelID;
public GameState() {
    stateID = 2;
    levels = new ArrayList<Level>();
    createLevels();
    currentLevelID = 0;
}


创造关卡

    public void createLevels(){
    try {
        this.levels.add(new NormalLevel(0, 10, 10, null, null, new EmptyTile(1, 1, 1, 1, null) ));
    } catch (IOException e) {
        e.printStackTrace();
    }
}


使用这段代码(忘了技术术语大声笑)

    //level is the superclass of normallevel or whatever i named the default level
    public Level(int id, int height, int width, ArrayList<TileEntity> tiles, ArrayList<MobileEntity> mobiles, TileEntity fillBlock){
    this.height = height;
    this.levelID = id;
    this.width = width;
    if(tiles != null){
        this.tiles = tiles;
    } else {
        tiles = new ArrayList<TileEntity>();
        try {
            tiles.add(new EmptyTile(-50,-50,1,1,null));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if(mobiles != null){
        this.mobiles = mobiles;
    } else {
        mobiles = new ArrayList<MobileEntity>();
        try {
            mobiles.add(new DefaultEntity(-50,-50,1,1,null));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if(fillBlock != null){
        this.tiles = new ArrayList<TileEntity>();
        this.fillWith(fillBlock);
    }
}
public void fillWith(TileEntity tile){
    for(int i = 0; i < this.height; i++){
        for(int j = 0; j < this.width; j++){
            for(int k = 0; k < this.tiles.size(); k++){
                if (this.tiles.get(k).y == i && this.tiles.get(k).x == j){
                    break;
                }
                if(k == this.tiles.size()){
                    tile.x = j;
                    tile.y = i;
                    this.tiles.add(tile);
                }
            }
        }
    }
}


然后我尝试更新水平

    public void update(){
    this.draw();
    for(int i = 0; i < this.tiles.size(); i++){
        this.tiles.get(i).update();
    }
    for(int i = 0; i < this.mobiles.size(); i++){ //nullpointerexception here
        this.mobiles.get(i).update();
    }

    this.specialUpdate();
    }


但是我在注释行上出错。我很困惑,地狱,帮助将不胜感激:)

最佳答案

您的mobiles对象为null,因为在以下代码中

if(mobiles != null){
        this.mobiles = mobiles;
} else {
    mobiles = new ArrayList<MobileEntity>();


在其他情况下,您分配局部变量mobiles而不是this.mobiles

09-11 18:12