how to acess Static variable in other scripts without extended functions?

must I really do a separate function for accessing other static variables and changing them?

what IF I’d need to access 30 different static variables not for reseting.

would I have to make 30 functions?

it’s made like:

// CreateFloorScript
public static bool Winner = false;
// MainMenuScript
MasterCreateFloorScript.Winner = false;

Assets/Scripts/MainMenu.cs(34,65): error CS0176: Static member `CreateFloor.Winner' cannot be accessed with an instance reference, qualify it with a type name instead

so I did a work around:

// MainMenuScript
MasterCreateFloorScript.ResetF();

and in the script

// CreateFloorScript
public void ResetF (){
    Winner = false;
}
1 Like

You access a static variable in a class this way:

{class name}.{static member name}

So if this is the case:

public class CreateFloorScript: MonoBehaviour {
  public static bool Winner = false;
}

Then you access Winner from any script like this:

 CreateFloorScript.Winner = true;
 if(CreateFloorScript.Winner == true) ...

You don’t need to make a function to access a public static variable from outside the class. However, in many cases it will be good practice, and it might be a good idea to ask yourself why you are using so many statics.

public class SomeClass {
    public static int someInt = 0;
}

public class SomeBehaviour : MonoBehaviour {
    public static int AnotherInt = 0;
    public void Awake() {
        SomeClass.someInt = 1;
        AnotherInt = 2;
    }
}

From the code snippet provided, it looks like you are trying to do the assignment via an instance of the class, not the main class:

public class BadClass : MonoBehaviour {
    public SomeClass someClass;
    void Awake() {
        someClass.someInt = 1; // This will not compile. someInt isn't an instance variable
        SomeClass.someInt = 1; // This will. someInt belongs to the class SomeClass. You don't need a reference
    }
}

The problem with using statics is that external classes can mess with the state of your class and not tell you about it, or input invalid data/etc. By wrapping the assignments in a function (or setter/getter), you can ensure that you update the internal state, as well as validate the input/etc.

Also note that using statics as opposed to a singleton structure will not let you see the values in the inspector (which you may or may not care about)