Reputation: 233
I'm working on an Android Game. Entire gameplay is in "Gameplay" class. The problem is when i want to have start again option and i have no idea how to remove "mg" object from "Gameplay" class and make a new one. Here is my code:
package com.PJA.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class GameScreen extends BaseScreen {
static short state=1;
Gameplay mg;
Menu mm;
LostScreen ls;
public GameScreen(Gra game) {
super(game);
mm=new Menu();
mg=new Gameplay();
ls=new LostScreen();
}
public void update() {
if(state==1) mm.live();
if(state==2) mg.live();
if(state==3) ls.live();
Gdx.app.log("CurrentState: ", Integer.toString(state));
}
public void drau(SpriteBatch sb) {
if(state==1) mm.show(sb);
if(state==2) mg.show(sb);
if(state==3) ls.show(sb);
}
}
Upvotes: 0
Views: 3219
Reputation: 328624
It's often a bad idea to initialize all fields in the constructor. While it feels natural, it limits reuse. It's often better to create a dedicated init()
or reset()
method:
public GameScreen(Gra game) {
super(game);
reset();
}
public void reset() {
mm=new Menu();
mg=new Gameplay();
ls=new LostScreen();
}
Upvotes: 0
Reputation: 597124
mg = new Gameplay()
this will create a new instance that will replace the old one (which will eventually be garbage-collected)
Another option, which is way more verbose, is to write a .reset()
method that sets all fields of Gameplay
to their initial values. This will give you better control over which fields you want to reset, but if you want everything - just create a new instance of Gameplay
Upvotes: 0