0

I'm making a game. I have an instance of my player class which holds all of the player's info. How can I reference this particular instance from anywhere?

  • 1
    Sounds like you want a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern). Be careful using it. – bradimus Oct 26 '16 at 19:43
  • 2
    https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java – Matt Oct 26 '16 at 19:43
  • Sounds like you *think* you want a singleton, but you really don't. Pass the instance of the `Player` class around to the places you want it. – Andy Turner Oct 26 '16 at 20:57

1 Answers1

0

make an object as public static eg

public static Player player = new player();
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • What happens when someone decides to reassign that variable? – bradimus Oct 26 '16 at 19:45
  • The question doesn't state that he wants to reassign it he just want an object to store all info please look at the question – Rahul Singh Oct 26 '16 at 19:47
  • 2
    I understand what he wants. Your solution is a poor one. `Player.player = null;` could be called at any point by any class. Now, how does a new class get access to the original 'global' instance? Any class could call `Player.player = new Player();` Oops. No more global instance. Implementing a singleton needs to be done with care, and this is not how it is done. See https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java – bradimus Oct 26 '16 at 19:53