Disclaimer: you could make Player
a static
class, which would probably behave how you want, but doing so is ill-advised as it limits you to a single player object and can't easily be unit tested, amongst other problems. See When to use static classes in C#.
You have to understand that you Player
is a class. Think of it as a blueprint for how a Player
object should look. I usually go to a car analogy for this: you buy two Toyota Priuses. Identical in every way. You take one to a spray shop and have a design painted on it. Has the other Prius changed? No. It's the same with var player1 = new Player(); var player2 = new Player();
- they are both of type "Player", but they are not the same player.
Now consider your AddMoney method:
public static void AddMoney()
{
var NewPlayer = new Player();
NewPlayer.money += 1500;
}
You're creating a player that only exists within the AddMoney
method. Once outside, it effectively doesn't exist anymore (stuff isn't deleted from memory immediately, but garbage collection isn't a topic you should be concerned with just yet).
Since Player
is a class
, it's a reference type, which means that passing it to a method will pass a reference to the same object in memory. This means that we can change the object in AddMoney
and it will be reflected in the caller. Note that we can't replace the object - for that you would need the ref
keyword (but that's another topic too).
public static void AddMoney(Player player)
{
player.money += 1500;
}
Example:
var player = new Player();
player.money = 8500;
Console.WriteLine(player.money); // 8 500
AddMoney(player);
Console.WriteLine(player.money); // 10 000
Try it online
Alternatively, if you want to create a player, you could create a factory method:
public static Player CreatePlayer()
{
return new Player
{
money = 1500
};
}