# render() can't seem to reference my sprite properly

This is driving me a little crazy. We use libGDX, working on making a simple side scroller for fun. I've got it switching from screens alright, loading from my main menu into my level one class, which implements screen.

public class levelOne implements Screen


Don't know if that effects this. When I try to initialize my sprite, my editor (AIDE) highlights it. Gives me an error saying that there is no access to the variable, as it does when you declare something but don't use it.

Texture faceTexture = new Texture(Gdx.files.internal("faceSprite.png"));
faceGuy = new TextureRegion(faceTexture, 50, 50, 95, 95);
Sprite player = new Sprite(faceGuy);


I do actually call up the sprite in render() though,

batch.begin();

// Background
batch.draw(backGround,0,0,2900,800);

// Player
player.draw(batch);

// Enemies

batch.end();


It doesn't generate an error there, but trying to run it generates a crash. I can do a batch.draw of the texture, but every attempt at doing it as a sprite fails. I have it being initialized in show(), thought maybe making a new method to do so would help, but had the same result. The only way I've managed to make it work was to initialize it in render(), but that not only resets the sprites position multiple times a second, but I expect is also a memory hog. Help!

• Please post the stack trace of your error since it's pretty difficult to understand what your problem is right now. But from what I can tell you are declaring player as a local variable, not an instance variable. Try putting Sprite player; at the top of your class and then change Sprite player = new Sprite(faceGuy); to player = new Sprite(faceGuy). – Charanor Nov 27 '17 at 17:30

Solved it! I'm working on Android so logging is an issue, couldn't do that. And the local variable issue was correct, made the warning go away, thanks. Didn't solve the crashing.

What it ended up being was my screen switching. I have a spritebatch in a previous screen, which for convenience I also named batch. I wasn't handling my assets well, caused a crash when trying to reference the sprites. Solution was easy - on my previous screen, when I switch, make sure to also dispose of the spritebatch.

((Game)Gdx.app.getApplicationListener()).setScreen(new levelOne());


batch.dispose();

...managing resources is important.

• Be careful if you are planning on going back to this screen if you are reusing the reference since your batch will now be disposed. – LAMonday Nov 28 '17 at 15:55
• Thanks for coming back and answering your question! It would be very helpful for the community if you could mark this as the accepted one :) – Vaillancourt Dec 2 '17 at 1:17