1

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.

3
  • In gameMaanager.cs make a reference for generalManager.cs and assign it (If using Unity like it looks make a public reference and assign it in the inspector/editor) Commented Jul 3, 2022 at 11:42
  • You need to do something like var myManager = new generalManager(); var eggs = generalManager.getEggs(); As a side note: C# normally uses properties rather than bare getter/setter functions. Also StyleCop recommendations are to use PascalCase rather than camelCase in C#. Commented Jul 3, 2022 at 12:25
  • You error indicates you need to reference the object by an instance of the object. So you would need code like Manager manager = new Manager(); Eggs eggs = manager.eggs = new Eggs(); Commented Jul 3, 2022 at 13:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm in the case where I need to have the object GeneralManager in multiple classes so I'll stay with static yeah that's a good idea, thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.