Boolean function inside a class not working

Hey there i was creating an animation for a simple game im working on and run into a problem where my simple boolean function inside a class returns an error “NullPointerException”

int  randomHue;
int rainbowHue;

boolean draw_startup_TaskAnim = false;

color bgr = color(230, 230, 250);

TaskAnim startup_TaskAnim;

void setup () {
  size(450, 800);
}


void draw () {
  colorMode(RGB);
  background(bgr);


  if (draw_startup_TaskAnim) {
    startup_TaskAnim.grow();
    startup_TaskAnim.display();
  }




  if (startup_TaskAnim.end() == true) {
    draw_startup_TaskAnim = false;
    fill(color(randomHue, 80, 90));
    rect(width / 2, height / 2, 25, 25);

    println("**works**");
  }
}

void mousePressed() {

  randomHue = randomHue();
  startup_TaskAnim = new TaskAnim (100, 20, 0, 5, width * 2, color(randomHue, 80, 90));
  draw_startup_TaskAnim = true;
}


class TaskAnim {
  float xpos;
  float ypos;
  float animSize;
  float maxSize;
  float growth;

  color animFill;

  TaskAnim(float temp_xpos, float temp_ypos, float temp_animSize, float temp_growth, int temp_maxSize, color temp_animFill) {

    xpos = temp_xpos;
    ypos = temp_ypos;
    animSize = temp_animSize;
    growth = temp_growth;
    maxSize = temp_maxSize;

    animFill = temp_animFill;
  }


  void display () {
    colorMode(HSB, 100);
    fill(animFill);
    stroke(animFill);
    ellipse(xpos, ypos, animSize, animSize);

    colorMode(RGB);
    fill(bgr);
    noStroke();
    rect(0, height /10 + 1, width, height);
  }

  void grow () {

    animSize = animSize + growth;
  }


  void growStop () {
    growth = 0;
  }



  boolean end () {    
    if (animSize > maxSize) {
      return true;
    } else {
      return false;
    }
  }
}




int randomHue() {  
  colorMode(HSB, 100);
  randomHue = int(random(1, 100));
  return randomHue;
}

Maybe this is causing the error?

Because you define / instantiate it only in mousePressed()

So in draw() it is null

The boolean function looks okay

2 Likes

As @Chrisir said, you are trying to access method of an object that is not created so it does not exist in memory and thus the NullPointerException.

To prevent that, you can add the following piece of code at the beginning of your draw() loop:

if (startup_TaskAnim == null) {
  return;
}

Or simply create the object in the setup() method.

3 Likes

Thans a lot for your help and fast reply, i just couldnt see this basic mistake before.

2 Likes