Jon
Jon

Reputation: 295

C# Class objects resetting?

I think I may know what my problem is, but I'm not sure how to solve it. I've tried to google it, but no look...

Let's say I have 3 classes; menu, shop and player. When you buy something from the shop, it gets added to your inventory in the player class and then you go back to the main menu. You then choose to view your inventory.

I have all this working, but when I choose to view my inventory at the main menu, it has nothing inside of it. I know it works, cause I've printed my inventory out in the shop after I've bought an item.

I think it's because I'm making a new object in the menu and shop classes?

Menu.cs

Shop shop = new Shop();
Player player = new Player();

Shop.cs

Menu menu = new Menu();
Player player = new Player();

I think the problem is when I'm sending the user back to the menu after they've bought an item, it creates a new Player object which sets all their variables back to default?

I don't know too much about classes and objects, as I learn by doing. But is there a way to make it so it doesn't reset itself once you go back to the menu?

Upvotes: 0

Views: 2523

Answers (2)

Score_Under
Score_Under

Reputation: 1216

Instead of storing the Player object in each of those classes, create only one Player object (that is, use new Player() only once), in some important class (e.g. main menu? main class?).

Then, to access this Player from your Shop and Menu, pass it in as a constructor parameter:

private Player player;

public Shop(Player player, OtherStuff here) {
    this.player = player;
}

Upvotes: 2

Daniel Möller
Daniel Möller

Reputation: 86600

Yes, when you do new Anything(), it's a fresh new instance with default options and values.

One way to solve it is to pass the Player instance to the Shop when you buy. (Shop doesn't need to have a player declared inside it, just need to use an existing player). And in that Player you passed to the Shop, you add the things bought to the inventory.

Upvotes: 2

Related Questions