- Home /
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;
}
Answer by nsxdavid · Mar 18, 2013 at 05:46 AM
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) ...
Answer by Tarlius · Mar 18, 2013 at 06:01 AM
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)
Your answer
Follow this Question
Related Questions
Can't access a javascript static variable from c# script 1 Answer
Access static variable c# 1 Answer
Change static variable in JS through Csharp 1 Answer
Accessing variable from a method in another script and gameObject 2 Answers
Can I access variables of scripts that inherit from abstract classes? 2 Answers