0

I'm trying to make a simple 3d game in Processing but I've run into a problem. I tried to make an array to keep track of my environment objects and to make it easier to modify. However, when I try to run the program, it won't work.

Main code:

  //arrays
BoxCl[] envArr;

void setup() {
  size(640, 360, P3D);

  envArr[0] = new BoxCl(1,1,-1,1);              //it shows the error here
  envArr[envArr.length] = new BoxCl(2,1,-1,1);
}

void draw() {
  background(0);
  camera(mouseX, height/2, (height/2) / tan(PI/6), width/2, height/2, 0, 0, 1, 0);
  Update();
  Draw();
}

void Update(){

}

void Draw(){
  for(BoxCl i : envArr){
    i.Draw();
  }
}

BoxCl Class:

class BoxCl{

  float x, y, z;
  int s;

  BoxCl(float x, float y, float z, int size){
    this.x = x;
    this.y = y;
    this.z = z;
    this.s = size;
  }

  void Draw(){
    translate(scale*x, scale*y, scale*z);
    stroke(255);
    fill(255);
    box(s * scale);
    translate(scale*-x, scale*-y, scale*-z);
  }

}

I've tried looking it up (here for example) but I think I'm too inexperienced to understand what I am supposed to do.

Please help.

edit: I am aware that a variable/array/object should be defined before being used. But how do I define the envArr in a way that it can still change? (i.e. increase or decrease in size when I have to create or delete an object)

Mr.Dude __
  • 37
  • 1
  • 10

1 Answers1

1

Your envArr variable is null. You have to initialize it to something before you use it.

You probably want something like this:

BoxCl[] envArr = new BoxCl[10];

Shameless self-promotion: I wrote a tutorial on arrays in Processing available here. You should also get into the habit of debugging your code by adding println() statements or stepping through your code with the debugger. For example, if you had printed out the value of envArr before the line that throws the error, you would have seen for yourself that it was null.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • What do I do when I don't know the final size of the array though? Because in this case, it restricts the amount of objects than can/have to be used. – Mr.Dude __ Jan 01 '18 at 18:16
  • 1
    @Mr.Dude__ Don't use array, use `ArrayList` if you don't know how long can it grow – Greggz Jan 01 '18 at 18:25
  • 1
    @Mr.Dude__ You can use Processing's `append()` function. More info in [the reference](https://processing.org/reference/append_.html). Or better yet, use an `ArrayList`. [Here](http://happycoding.io/tutorials/processing/arraylists) is a tutorial on ArrayLists in Processing. – Kevin Workman Jan 01 '18 at 18:28
  • @KevinWorkman Thanks, it's all working now. I used your Arraylist tutorial and it's running smoothly. Nice site btw :) – Mr.Dude __ Jan 01 '18 at 18:56