In this game, I am trying to have multiple lasers spawn at given coordinates, but for some reason, the app crashes every time the numLasers is greater than 1. I have tried everything, and I could really use some help.
Here is my code:
public class LaserSpawn {
private int amountOfVisibleLasers;
private Context context;
private long timeLastCreatedLaser;
private Laser[] holderLaser;
public LaserSpawn(Context context, int numLasers){
this.context = context;
holderLaser = new Laser[numLasers];
this.amountOfVisibleLasers = numLasers;
for(int i = 0; i< numLasers; i++){
holderLaser[0] = new Laser(context, -10, -10);
}
}
public void updatePlayerLaser(boolean shootLaser, float x, float y) {
// Check if a new Laser should be created
if(shootLaser == true) {
if(timeLastCreatedLaser + 100 < System.currentTimeMillis()) {
timeLastCreatedLaser = System.currentTimeMillis();
boolean createdNewLaser = false;
for(int i = 0; i < this.amountOfVisibleLasers; i++) {
if(createdNewLaser == false) {
if(holderLaser[i].isDisposed()) {
this.generateNewLaser(i,x,y);
createdNewLaser = true;
}
}
}
}
}
// Update all the other Lasers
for(int i = 0; i < this.amountOfVisibleLasers; i++) {
if(holderLaser[i].isDisposed() == false) {
holderLaser[i].update();
}
}
}
private void generateNewLaser(int i, float x, float y) {
holderLaser[i].setY(y);
holderLaser[i].setX(x);
}
Thanks!
I’m pretty sure this is your problem:
You only ever create a
new Laserin the first position of your array. If you try access a second one you’ll get anull pointer exception.It should be something like