Search code examples
c#unity-game-enginestaticpublic

Need a public class in unity but forced to add static


I want to make a variable editable in the unity inspector by scripting it as a public var - for example, public int days = 3 - and then having another private variable that uses days (and turns a user-friendly input into a number that is now useful to my code) such as private int hours = days * 24. However I am forced to make days a public static int for it to be accessible by the hours equation. This means that it is no longer available to change in the inspector. This is, I think, a fundamental problem with my understanding of c#, and any tips for what I should instead be doing would really help a beginner out.

public int days = 3;
private int hours = days * 24;

Thanks!


Solution

  • It would have been much more better if you provided a complete script example. By reading your question carefully, this is what you are currently doing:

    public int days = 3;
    private int hours = days * 24;
    

    Initialize the hours variable in a function and that should be fine. The Start or Awake function are usually used for something like this:

    public int days = 3;
    private int hours;
    
    void Start()
    {
        hours = days * 24;
    }
    

    This is because to initialize a variable with another variable, the one you are using to initialize the other one must be a static or const variable.

    This example with const would have worked too:

    public const int days = 3;
    public int hours = days * 24;