我在尝试访问我在不同类中创建的一个变量时遇到问题。
我有一个 GameScene 类,我在其中创建一个新类:
npcArray[0] = new Npc(-100, 100, vbom, camera, physicsWorld, 0);
在 npcArray[0] 中,我想访问在上一个类中创建的变量。 我如何访问它?
编辑1:
第一类:
public class GameScene extends BaseScene implements IOnSceneTouchListener, IOnAreaTouchListener {
public Npc[] npcArray = new Npc[4];
public Bullet[] bulletArray = new Bullet[500];
public static Zombie[] zombieArray = new Zombie[50];
//code...
private void createNPCs(){
npcArray[0] = new Npc(-100, 100, vbom, camera, physicsWorld, 0);
attachChild(npcArray[0]);
registerTouchArea(npcArray[0]);
npcArray[1] = new Npc(200, 100, vbom, camera, physicsWorld, 1);
attachChild(npcArray[1]);
registerTouchArea(npcArray[1]);
}
第二类:
public class Npc extends Sprite{
//code...
if(distanciaMinima <= 3 && distanciaMinima != -1 && timer >= 200 ){
timer = 0;
Vector2 vectorUnitariBullet = new Vector2(GameScene.zombieArray[zombieProper].body.getPosition()).sub(body.getPosition()).nor();
GameScene.createBullet(ArrayPosition, vectorUnitariBullet, accuracy);
}
}
因此,当我访问 npcArray["number"] 时,我想访问变量bulletArray 或任何方法示例:“GameScene.createBullet()” *现在它是错误的
编辑2:
我的代码结构引用了这个游戏:Game Code文末下载
我正在尝试访问在 Player 中时在 GameScene 中创建的变量。
抱歉我的英语不好。
最佳答案
添加对 Npc 的 GameScene 引用。并编辑你的构造函数。
Class Npc
{
public GameScene gs;
public Npc(int x, int y, ..... , GameScene gs)
{
this.gs = gs;
}
}
使用以下术语通过构造函数传递游戏场景:
npcArray[0] = new Npc(-100, 100, vbom, camera, physicsWorld, 0, this);
访问它:
npcArray[0].gs.variable_name
注意这不会导致额外的内存分配。
关于Java 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19252865/