PImage and img=null;

I cobbled this together from something @Chrisir once wrote. I only have one small question. What, if anything, does img=null; do? It is at the end of the setup() block.

PShape globe;
PImage img;

void setup() {
  size (600, 600, P3D);
  
  img = loadImage("test.jpg");
  
  globe = createShape(SPHERE, 100);

  globe.setStroke(false);

  globe.setTexture(img);

  img=null; // what is this?
}

void draw() {
  
  background(0);

  translate(width/2, height/2); 
  
  rotateY(map(mouseX, 0, width, 0, TAU));
  rotateX(map(mouseY, 0, height, 0, TAU));

  shape(globe, 0, 0);
}
1 Like

if you use a picture of notable size
and try that code with or without that line
you could check on the by your running code use memory.
i do see here ( win 10 ) some small difference.

2 Likes

PImage is an object and by setting it null I make sure it has an initial value. But no image in it

But maybe it’s null automatically (its default) - I don’t know.

But sometimes I check if(img!=null) to control if the loading of the image was successful

For null see reference I guess

1 Like

Thanks @Chrisir
So, should img=null; come earlier in the block, before the loadImage()? Or doesn’t it matter?

Ah, I see.

Since I don’t need the image anymore after copying it to globe, I deleted it afterwards to make clear it’s not used anymore. And it saves a bit of memory

It could also be a local variable in setup

2 Likes

Or even better, just pass the loaded PImage as an argument for the PShape: :bulb:
globe.setTexture(loadImage("test.jpg"));

That depends whether the PShape object keeps the passed PImage reference to itself. :roll_eyes:

3 Likes

Now I understand! @Chrisir Thank you.

@GoToLoop
Is the idea to get rid of the img completely?
Like this:

PShape globe;

void setup() {
  size (600, 600, P3D);

  globe = createShape(SPHERE, 100);

  globe.setStroke(false);

  globe.setTexture(loadImage("test.jpg"));
}

void draw() {
  background(0);
  
  translate(width/2, height/2); 

  rotateY(map(mouseX, 0, width, 0, TAU));
  rotateX(map(mouseY, 0, height, 0, TAU));

  shape(globe, 0, 0);
}
2 Likes

Yup! If some value is gonna be used in loco only, we don’t need to store it in some variable. :grinning:

3 Likes