#static in games with examples?

1 messages · Page 1 of 1 (latest)

twilit patio
#

I'm a bit confused on when to use static or not, In a small game I made I used the static keyword once on a variable to acess that:
(PlayerMovement class) public static bool deathPlayer = false;
(Another class) PlayerMovement.deathPlayer = true;

summer lodge
#

no you should not use static for this

#

Get a reference to an instance of PlayerMovement

#

if you're in Unity that'd be with GetComponent method. if not in unity, then you pass the reference where you need it

twilit patio
#

by doing PlayerMovement <name> = new PlayerMovement()?

summer lodge
#

exactly

#

and then passing that variable around where necessary

twilit patio
#

so when exactly would it be fine to use static instead? Or more likely why is it bad?

summer lodge
#

sure. so the reason you wouldn't use static here is because a player being "dead" is not a trait inherent to the PlayerMovement class, it's inherent to specific players.

if you have trouble deciding, think about whether it's conceivable to have more than one instance. not necessarily that you do - but that it's possible to. in this case it is. because you could conceivably imagine two players being on the screen at one time (local/split screen multiplayer for example). two players, each have their own state to track. one could be dead, the other might not be