1

Using libgdx, I'm creating a 2D game. I want to load all textures to an array. So I've created a class for them. I'd like to loop the image array within the render():

public class LoadingImages {
    public Texture[] images;

    public area1() {
        images[0] = new Texture(Gdx.files.internal("img/image1.jpg"));
    }
}

This gives me and error when I try to run it:

Exception in thread "LWJGL Application" java.lang.NullPointerException
          at com.mygame.game.LoadingImages.loading(LoadingImages.java:31)

The number of images will be variable depending on the area.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Mateus
  • 11
  • 3
  • Please, provides the error you got – Damien Leroux Jun 16 '16 at 15:01
  • Exception in thread "LWJGL Application" java.lang.NullPointerException at com.mygame.game.LoadingImages.loading(LoadingImages.java:31) 31 is the line number at images[0] = new Texture(Gdx.files.internal("img/image1.jpg")); – Mateus Jun 16 '16 at 15:37
  • Thank you :). please update your question with it. – Damien Leroux Jun 16 '16 at 15:42
  • my goald is to create a class that can load all images, animations and sounds for a expecific area, to be able to draw the imagens at the render function, and since every area will have a diferente number of images, me idea is to load all images as textures pass it to and array and then make a for loop on the array at the render function – Mateus Jun 16 '16 at 16:08

1 Answers1

2

See also What is a NullPointerException, and how do I fix it?.

You are trying to access a variable which you haven't assigned yet: images[0]. Before you can use the first element in an array you will have to create an array that is at least of size 1. So, change it to:

public *void* area1() {
    images = new Texture[1];
    images[0] = new Texture(Gdx.files.internal("img/image1.jpg"));
}

With that said, your exception does not match your code. Also, you might want to reconsider your approach, using many textures will quickly affect performance because it implies flushing the batch. It is better to pack your images into a single texture. If you like to access your images by index then that's still possible. See this.

Also AssetManager is much more convenient than manually loading all your assets. See this.

Community
  • 1
  • 1
Xoppa
  • 7,983
  • 1
  • 23
  • 34
  • My game is all 2d images and soud, area1 have 1 background image and some spryte animations on it, when the player go from area1 to area2 the background change but some sprite animations are the same and others are new, what will be the best approach?, Now I'm load the background as a single image, and the sprites animations as atlas textures. for each object animated – Mateus Jun 20 '16 at 10:05