我正在制作一个简单的RPG游戏,我一直试图在游戏中加入敌人。它在敌人的发现中加载所有它的统计数据,但是当我尝试渲染它时,我得到Exception in thread "Thread-2" java.lang.NullPointerException
at com.hosfordryan.tileRPG.entities.Enemy.render(Enemy.java:52)
at com.hosfordryan.tileRPG.Game.render(Game.java:134)
at com.hosfordryan.tileRPG.Game.run(Game.java:103)
at java.lang.Thread.run(Unknown Source)
。我已经使用JOptionPanes来确认敌人是否在arrayList中保存,因此无法进行。阅读敌人的代码是:
public static void loadEnemies() {
Scanner qwe;
try {
qwe = new Scanner(new File("enemyStats.txt"));
while (qwe.hasNextLine()) {
String name = qwe.nextLine();
String origin = qwe.nextLine();
String weapon = qwe.nextLine();
String gear = qwe.nextLine();
String spec = qwe.nextLine();
int hp = qwe.nextInt();
int att = qwe.nextInt();
int def = qwe.nextInt();
int randX = (int) (Math.random()*(20*SCALE*TILESIZE)); //Give random x coordinate
int randY = (int) (Math.random()*(20*SCALE*TILESIZE)); //Give random y coordinate
if(qwe.hasNextLine()){
qwe.nextLine();
}
enemies.add(new Enemy(randX,randY,im,name,origin,weapon,gear,spec,hp,att,def)); //adds enemy into arrayList
String temp = "";
temp+=enemies.get(enemies.size()-1).getName()+"\n"+enemies.get(enemies.size()-1).getRx(); //checking if saving into arrayList correctly
JOptionPane.showMessageDialog(null, temp);
}
for(int i = 0; i < enemies.size();i++){ //adds enemy to arrayList to be rendered
enemiestoRend.add( new Enemy(enemies.get(i).getRx(),enemies.get(i).getRy(),im,enemies.get(i).getName(),enemies.get(i).getOrigin(),enemies.get(i).getWeapon(),enemies.get(i).getGear(),enemies.get(i).getSpecialMove(),enemies.get(i).gethp()
,enemies.get(i).getAttack(),enemies.get(i).getDefense()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
渲染代码:
public void render(Graphics g){
g.drawImage(im.enemy, this.x*Game.TILESIZE * Game.SCALE, this.x*Game.TILESIZE * Game.SCALE, Game.TILESIZE * Game.SCALE,
Game.TILESIZE * Game.SCALE, null);
}
在main中渲染方法,渲染所有内容:
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if (bs==null) {
createBufferStrategy(3);
return;
}
Graphics g= bs.getDrawGraphics();
//Render Here
else if(Player.l1){
l1.render(g);
}
for(int i = 0; i < enemies.size();i++){
enemies.get(i).render(g);
}
for(int i = 0; i < enemiestoRend.size();i++){
enemiestoRend.get(i).render(g); //problem here
}
player.render(g);
//End Render
g.dispose();
bs.show();
}