Cannot use array variable defined in setup()

I want each of 30 lines to have a distinct random colour, but I get a ‘cols cannnot be resolved’ error in the draw() part.

//https://funprogramming.org/76-Slowly-morphing-bezier-curves.html
void setup() {
  size(500, 400);
  smooth();
  noFill();
  int [][] cols = new int[30][3];
  for (int i = 0; i < 30; i++) {
    for (int j = 0; j < 3; j++) {
      cols[i][j] = int(random(255));
    }
  }
}
void draw() {
  background(255);
  float t = frameCount / 100.0;
  for (int i = 0; i < 30; i++) {
    stroke(cols[i][0], cols[i][1], cols[i][2]);
    bezier(
      width/2, height, 
      width/2, noise(1, i, t)*height, 
      noise(2, i, t)*width, noise(4, i, t)*height, 
      noise(3, i, t)*width, noise(5, i, t)*height
    );
  }
  // https://processing.org/reference/saveFrame_.html
  saveFrame("line-######.png");
}

Hi,

You are declaring cols inside of setup() so it exists only within it. If you want it to be also recognized in draw(), then you need to declare it outside of setup().

int [][] cols;

void setup() {
  size(500, 400);
  smooth();
  noFill();
  cols = new int[30][3];
  for (int i = 0; i < 30; i++) {
    for (int j = 0; j < 3; j++) {
      cols[i][j] = int(random(255));
    }
  }
}
void draw() {
  background(255);
  float t = frameCount / 100.0;
  for (int i = 0; i < 30; i++) {
    stroke(cols[i][0], cols[i][1], cols[i][2]);
    bezier(
      width/2, height, 
      width/2, noise(1, i, t)*height, 
      noise(2, i, t)*width, noise(4, i, t)*height, 
      noise(3, i, t)*width, noise(5, i, t)*height
    );
  }
  // https://processing.org/reference/saveFrame_.html
  saveFrame("line-######.png");
}

If you want more info, try looking for variables scope.

2 Likes

Brilliant, thank you, I knew it was simple :slight_smile:

1 Like