我正在从事 android 游戏开发
我的模型包中有一个名为 droid 的类 我的主游戏面板类中有一个名为 update() 的构造函数
我想创建一个机器人数组,并在我的主游戏面板和主游戏面板类中的构造函数中访问它们。 我可以从主游戏面板构造函数执行此操作,但不能从更新构造函数执行此操作。即每当我尝试访问主游戏面板类的更新构造函数中其中一个机器人的 x 位置时,我都会收到此错误: “表达式的类型必须是数组类型,但它解析为 Droid”
package net.test.droid.model;
public class Droid {
private Bitmap bitmap; // the actual bitmap
private int x; // the X coordinate
private int y;
private boolean touched; // if droid is touched/picked up
public Droid(Bitmap bitmap, int x, int y) {
this.bitmap = bitmap;
this.x = x;
this.y = y;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void draw(Canvas canvas) {
canvas.drawBitmap(bitmap, x, y, null);
}
}
在主游戏
public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback {
public Droid droid_array;
public MainGamePanel(Context context) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
Droid[] droid_array = new Droid[5];
for (int i = 0; i < 5; i++) {
droid_array[i] = new Droid(BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher), droid_x_pos + i*10, droid_y_pos);
}
droid_array[1].setX(666);
}
最后一行工作正常,但是当我尝试在 update() 中使用它时,出现错误
public void update() {
test=droid_array[1].getX();
}
上面的行返回错误“表达式的类型必须是数组类型,但它解析为 Droid”
最佳答案
这是您的问题:
public Droid droid_array;
具有类型Droid
。这是您的类(class)级别的属性(property)。在 MainGamePanel
构造函数中,您可以使用以下变量隐藏类级别属性:
Droid[] droid_array
一旦离开 MainGamePanel
构造函数,Droid[] droid_array
变量就会超出范围。
Update 方法引用 public Droid droid_array
类属性,该属性不是数组。
关于java - java中如何访问对象数组中的对象中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18703816/