We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have created an object array, and I use the seconds on my computer clock to count the array. No matter what, when the array hits over 0, I get a null pointer exception error with no explanation in the error feed. Here is my code.
Box b1;
int i = 0;
float t = random(800);
Obstacle[] obs = new Obstacle [61];
void setup() {
size(1000,1000);
b1 = new Box(10,500);
obs[i] = new Obstacle(1000,t);
frameRate(60);
}
void draw() {
println(i);
background(100);
b1.display();
b1.move();
obs[i].display();
obs[i].move();
if (i == 0) {
i = second();
}
}
Answers
https://forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text
You have instantiated only 1 Obstacle, and assigned it to obs[]'s index 0 (i is
0
while in setup()).So as soon as variable i is assigned to anything else but
0
, and you attempt to accessobs[i]
, you've got yourself an NPE (NullPointerException)! :-&what do you suggest I do to fix this
Instantiate as many Obstacle as obs[]'s length: *-:)
https://Processing.org/reference/Array.html
I moved my obstacle initialization to my draw loop and I am no longer getting the error, but now the object won't show up... New thread? lol
That was exactly the wrong thing to do.
Use a for loop, instantiate all the objects. Do this in setup.
@birdie_22 -- No, stay in this thread.
Don't initialize or load in draw(). Draw is called (by default) 60 times a second. So you are re-initializing 60 times per second (bad).
As GoToLoop pointed out, your original code above says:
That code doesn't make sense. There is no such thing as obs[37], because you only created a single obstacle, not 60.
You may want to fix by making a for loop around this line and creating a new Obstacle for i = 0-59:
... and you might want to randomize t inside that for loop as well, rather than only once.
If you don't want to instantiate an object rough every second rather than all the objects in one go in setup then use an integer to keep track of how many objects have been created