Search Unity

Question Unity Game: An object reference is required for the non-static field, method, or property

Discussion in 'Scripting' started by caprarugabriel, Mar 13, 2023.

  1. caprarugabriel

    caprarugabriel

    Joined:
    Oct 7, 2021
    Posts:
    1
    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

    Code (CSharp):
    1. public class Game : MonoBehaviour
    2. {  
    3.     public int coal = 0;
    4.     public int multiplier = 1;
    5.     public int upgradeprice = 10;
    6.     public int coalprice = 1;
    7.     public int uplvl = 1;
    8.     public int money = 1;
    ...

    The void where I got this error:

    Code (CSharp):
    1.     public void Increment() {
    2.         Game.coal += Game.multiplier;
    3.         PlayerPrefs.SetInt("coal", Game.coal);
    4.     }

    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:


    Code (CSharp):
    1. public class PlayerData
    2. {
    3.     public int coal;
    4.     public int multiplier;
    5.     public int upgradeprice;
    6.     public int coalprice;
    7.     public int uplvl;
    8.     public int money;
    9.  
    10.     public PlayerData (Game m) {
    11.         coal = m.coal;
    12.         multiplier = m.multiplier;
    13.         upgradeprice = m.upgradeprice;
    14.         coalprice = m.coalprice;
    15.         uplvl = m.uplvl;
    16.         money = m.money;
    17.     }
    18. }
    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.