I'm doing something wrong and can't get it figured out. I have an array of texture regions. I initialize the array in the constructor with elements from another texture region array in another class. This works fine.
我做错了什么事,弄不明白。我有一个纹理区域数组。我用另一个类中的另一个纹理区域数组中的元素初始化构造函数中的数组。这是很好。
Then in my update method I want to replace the objects in the array with different random ones from the array in the other class. This fails with a null pointer exception. Anyone can push me in the right direction? Code below.
然后,在我的更新方法中,我想用其他类中的数组中的不同随机变量替换数组中的对象。这在空指针异常中失败。有人能把我推向正确的方向吗?下面的代码。
Level1 lvl1 = new Level1();
//initialize local array with objects from array in lvl1
shapes = new TextureRegion[4];
txt1 = new TextureRegion(lvl1.shapes[0]);
txt2 = new TextureRegion(lvl1.shapes[1]);
txt3 = new TextureRegion(lvl1.shapes[2]);
txt4 = new TextureRegion(lvl1.shapes[3]);
shapes[0] = txt1;
shapes[1] = txt2;
shapes[2] = txt3;
shapes[3] = txt4;
The above works. Then the update method:
上述工作。然后更新方法:
for (int x = 0; x < 4; x++) {
int rnd = random.nextInt(15);
System.out.println(rnd);
shapes[x] = lvl1.shapes[0];
}
This generates a null pointer exception. For testing purposes i just try to access the first object. The 0 should be replaced by rnd
later.
这将生成一个空指针异常。为了测试目的,我只是尝试访问第一个对象。后面的0应该被rnd替换。
2 个解决方案
#1
0
It appears that the problem is here :
看来问题在这里:
Level1 lvl1 = new Level1();
You initialize a local variable in the constructor, and in the update method you are accessing an uninitialized instance variable (lvl1.shapes[0]1
), which throws NullPointerException
.
在构造函数中初始化一个局部变量,在更新方法中,您正在访问一个未初始化的实例变量(lvl1. size[0]1),它抛出NullPointerException。
Change it to :
把它改成:
lvl1 = new Level1();
in order to initialize the instance variable.
为了初始化实例变量。
#2
0
It seems I have solved the issue immediatly after posting this. I had to change the Aray in the lvl1 class to Static. Then it works.
看来我在发布这篇文章后马上就解决了这个问题。我必须将lvl1类中的Aray改为Static。它的工作原理。
#1
0
It appears that the problem is here :
看来问题在这里:
Level1 lvl1 = new Level1();
You initialize a local variable in the constructor, and in the update method you are accessing an uninitialized instance variable (lvl1.shapes[0]1
), which throws NullPointerException
.
在构造函数中初始化一个局部变量,在更新方法中,您正在访问一个未初始化的实例变量(lvl1. size[0]1),它抛出NullPointerException。
Change it to :
把它改成:
lvl1 = new Level1();
in order to initialize the instance variable.
为了初始化实例变量。
#2
0
It seems I have solved the issue immediatly after posting this. I had to change the Aray in the lvl1 class to Static. Then it works.
看来我在发布这篇文章后马上就解决了这个问题。我必须将lvl1类中的Aray改为Static。它的工作原理。