So basically, I'm creating a game on a SurfaceView and I have these classes on my main CustomView:
private TitleScreen titleScreen;
private GameScreen gameScreen;
private PauseScreen pauseScreen;
private GameOverScreen gameOverScreen;
Each of these classes have a draw(Canvas canvas)
method, and is called when the user goes to another screen. But the thing is, I have a SoundPlayer
class that includes all of my sound effects using SoundPool. It will be used on all these classes. Is there actually a way that the SoundPlayer only loads once, then is available throughout these classes? Or do I have to call release()
and recall the constructor everytime I switch? Thanks in advance. :D
UPDATE (SOLVED):
So here's what I did. I created an instance of my SoundPlayer class:
public class SoundPlayerInstance {
private static SoundPlayer soundPlayerInstance;
private SoundPlayerInstance(){}
public static void createInstance(Context context){
soundPlayerInstance = new SoundPlayer(context);
}
public static SoundPlayer getInstance(){
return soundPlayerInstance;
}
}
On my main view, before I do anything, I call this in my constructor:
SoundPlayerInstance.createInstance();
Then, on any of my classes, I can just call it to play the sound:
SoundPlayerInstance.getInstance().playSound();
I think this will be useful not only for situations like these, but it can also be useful for developers (like me) that want to instantiate a class that is available throughout all other classes. Thanks to system32 for answering my question. :)
Is there actually a way that the SoundPlayer only loads once, then is available throughout these classes?
It's possible. Make SoundPlayer
class singleton.
public class SoundPlayer
{
private static SoundPlayer instance;
private SoundPlayer()
{
// Do some stuff
}
public static SoundPlayer getInstance()
{
if(instance == null)
instance = new SoundPlayer();
return instance;
}
}
To access globally, just call SoundPlayer.getInstance()