Initializing arrays within a method

I have this code:

PImage[] lol;
PImage thing;

void setup() {
  size(500,300);

  thing = loadImage("c_0.png");
  loadImages(lol, 12);
}

void loadImages(PImage[] p1, int size) {
  p1 = new PImage[size];

  for(int i = 0; i < size; i++) {
    p1[i] = thing;
  }
}

void draw() {
  image(lol[3], 30, 40);
}

However, this gives me a NullPointerException. Why? Can't I initialize the PImages inside a method?

Thank you for any help :)

Answers

  • edited November 2016 Answer ✓

    Parameters are also local variables. Once their function ends, local variables are gone too! :-&

  • Also, why would you need to have some array filled w/ the the same PImage?! :-/

  • I was trying to create a method for initializing spritesheets. My full code was this:

    void loadImages(PImage ss, String ssPath, PImage[] sprites, int sW, int sH, int boxW, int boxH) {
      ss = loadImage(ssPath);
      sprites = new PImage[sW * sH];
      for(int j = 0; j < sH; j++) {
        for(int i = 0; i < sW; i++) {
          sprites[j * sW + i] = ss.get(i * boxW, j * boxH, boxW, boxH);
        }
      }
    }
    

    I would run this method like this: loadImages(tileSS, "36086464-ocean-wallpaper.jpg", tileS, 7, 3, 50, 50);

    Thank you very much for answering! :)

  • edited November 2016 Answer ✓

    I'd go w/ something like this: *-:)

    // forum.Processing.org/two/discussion/19397/initializing-arrays-within-a-method
    // GoToLoop (2016-Nov-29)
    
    static final String FILENAME = "c_0.png";
    PImage[] sprites;
    
    void setup() {
      size(500, 300, FX2D);
      smooth(3);
      imageMode(CORNER);
    
      PImage sheet = loadImage(FILENAME);
      sprites = createTiles(sheet, 7, 3, 50, 50);
    }
    
    static final PImage[] createTiles(PImage img, int cols, int rows, int w, int h) {
      PImage[] tiles = new PImage[cols*rows];
      for (int r = 0; r < rows; ++r)  for (int c = 0; c < cols; ++c)
        tiles[cols*r + c] = img.get(c*w, r*h, w, h);
      return tiles;
    }
    
  • Thank you :) :ar!

Sign In or Register to comment.