2012-07-14 75 views
0

当我在参数中传递精灵并在方法中初始化该对象时,但引用的对象仍然为null,而我在方法中传递了该对象。这是我的方法。Sprite传递引用导致空指针异常使用引擎GLES2

public void createAndLoadSimpleSprite(Sprite sprite ,String name, 
     SimpleBaseGameActivity activity, int width, int height) { 

    BitmapTextureAtlas atlasForBGSprite = new BitmapTextureAtlas(
      activity.getTextureManager(), width, height); 
    TextureRegion backgroundSpriteTextureRegion = BitmapTextureAtlasTextureRegionFactory 
      .createFromAsset(atlasForBGSprite, activity, name, 0, 0); 
    sprite = new Sprite(0, 0, backgroundSpriteTextureRegion, 
      activity.getVertexBufferObjectManager()); 
    activity.getTextureManager().loadTexture(atlasForBGSprite); 

} 

这里我怎么称呼它。

createAndLoadSimpleSprite(defualtCageSprite,"bg.png", this, 450, 444); 

但访问defaultCageSprite仍然会抛出一个空指针异常...我不是如果肯定它是一个AndEngine问题。但是,如果没有什么工作,我们不能在AndEngine中将sprites作为参数传递吗?

回答

1

你必须改变你的方法来返回精灵对象:

public Sprite createAndLoadSimpleSprite(String name, 
    SimpleBaseGameActivity activity, int width, int height) { 

BitmapTextureAtlas atlasForBGSprite = new BitmapTextureAtlas(
     activity.getTextureManager(), width, height); 
TextureRegion backgroundSpriteTextureRegion = BitmapTextureAtlasTextureRegionFactory 
     .createFromAsset(atlasForBGSprite, activity, name, 0, 0); 
activity.getTextureManager().loadTexture(atlasForBGSprite); 

Sprite sprite = new Sprite(0, 0, backgroundSpriteTextureRegion, 
     activity.getVertexBufferObjectManager()); 

return sprite; 

} 

现在,您可以拨打:

defualtCageSprite = createAndLoadSimpleSprite("bg.png", this, 450, 444); 

不要忘了你的精灵附着在scene

+0

是的,我改变了这种方法完全一样的方式..但我需要在我的类的构造函数中传递精灵,以便每个对象都有自己的精灵引用。所以我想把Sprite作为参考。 – Waqas 2012-07-15 15:55:20

+0

我不明白你想达到什么目的,但这是一个JAVA问题,请尝试在你的问题中添加一个'java'标记。 – 2012-07-15 16:20:12

+0

你说得对。我的错 :)。再次忽略了变量的范围:)。谢谢 – Waqas 2012-07-15 16:57:01

3

这不是AndEngine问题。你正在处理Java的工作方式。 AFAIK不可能有输出参数。你需要做的是使用“返回”或创建字段来保存你的数据。

+0

你是对的。谢谢 – Waqas 2012-07-15 16:57:36