Search code examples
c#staticnon-static

C# access variable from another class without static


I'm trying to access some variables from different classes in one of my classes, I would like to be able to get the value and set the value of those variable from other classes.

Right now, I'm using static but I'm using it too much and I think that's not good practice.

So I'm trying to do with getters and setters but I can't make it work. Here is a small example of what I'm doing right now :

generalManager file

public float eggs ; 

public float getEggs(){
    return eggs ; 
}

gameManager file

generalManager.getEggs() ;

And I have this error :

Assets/Scripts/gameManager.cs : error CS0120: An object reference is required for the non-static field, method, or property 'generalManager.eggs')

And I have to admit that I don't know what can I do to do not have this error anymore.


Solution

  • You can access the variables of a class only in two ways:

    1. Make the variable static.
    public class GeneralManager
    {
        public static float Eggs;
    }
    

    and use the variable in the GameManager like GeneralManager.Eggs

    1. Create an object of that class in the second class. For example, the GeneralManager class will look like this
    public class GeneralManager
    {
        public string Eggs
    }
    

    and inside the GameManager, do this

    GeneralManager generalManager = new GeneralManager()
    float eggsLeft = generalManager.Eggs
    

    Note: In the second case, if you create multiple objects of the GeneralManager class, the value of eggs will be different in every instance. For example, if two of your classes have the generalManger object created and you update the value of Eggs from one class, the object in the other class will remain unchanged. In that case, use the 1st method.