Mateus
Mateus

Reputation: 11

libgdx can't load texture to array

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.

Upvotes: 1

Views: 281

Answers (1)

Xoppa
Xoppa

Reputation: 8123

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.

Upvotes: 2

Related Questions