0

I want to start this by pointing out that I'm a beginner in C#. I'm doing this for just a week. I started creating a game in Unity and today I tried to make a save/load system for it.

I followed a tutorial, did all the steps but at the final, i get this error:

Game.cs(22,9): error CS0120: An object reference is required for the non-static field, method, or property 'Game.coal'

Here are the important parts of Game.cs

public class Game : MonoBehaviour
{   
    
5     public int coal = 0;
6     public int multiplier = 1;
7     public int upgradeprice = 10;
8     public int coalprice = 1;
9     public int uplvl = 1;
10    public int money = 1;
...

The void where I got this error:


21    public void Increment() {
22        Game.coal += Game.multiplier;
23        PlayerPrefs.SetInt("coal", Game.coal);
    }

This void Increment is connected to a game object, where everytime I click it, i need to increase my coal.

If I set my public int to public static int, I get another error in my other script: PlayerData.cs(16,16): error CS0176: Member 'Game.coal' cannot be accessed with an instance reference; qualify it with a type name instead

My PlayerData script:

6 public class PlayerData
7 {
8      public int coal;
9      public int multiplier;
10     public int upgradeprice;
11     public int coalprice;
12     public int uplvl;
13     public int money;
14
15    public PlayerData (Game m) {
16        coal = m.coal;
17        multiplier = m.multiplier;
18        upgradeprice = m.upgradeprice;
19        coalprice = m.coalprice;
20        uplvl = m.uplvl;
21        money = m.money;
22    }
23 }

I'm sorry If i formatted the text wrong but I'm new on this platform. If anyone can help me i'll be grateful.

  • 1
    Does this answer your question? [CS0120: An object reference is required for the nonstatic field, method, or property 'foo'](https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop) - You need an instance of a `Game` object. – Timothy G. Mar 13 '23 at 17:39

0 Answers0