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?
Asked
Active
Viewed 639 times
0
-
1Sounds like you want a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern). Be careful using it. – bradimus Oct 26 '16 at 19:43
-
2https://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 Answers
0
make an object as public static eg
public static Player player = new player();

Rahul Singh
- 19,030
- 11
- 64
- 86
-
-
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
-
2I 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