- Home /
Difficulty Accessing Static Variable
I have declared a static string in one script component of a gameobject, and am trying to access it in a script component of another game object. The static string is declared here:
public class PlayerStatus : MonoBehaviour
{
public static string mainStatus = "1";
}
In the other script, I attempt to print the string to console and eventually use the string in some methods.
public class Player : MonoBehaviour
{
GameObject statusContainer;
string currentStatus;
void Start()
{
statusContainer = GameObject.Find("StatusContainer");
currentStatus = statusContainer.GetComponent<PlayerStatus>().mainStatus;
print(currentStatus);
}
}
The script as such gives the error:
"Static member `PlayerStatus.mainStatus' cannot be accessed with an instance reference, qualify it with a type name instead"
I've tried putting the script containing the static string into the Standard Assets folder to make sure it gets compiled first, so that's not a problem.
Answer by Meltdown · Jul 18, 2012 at 06:49 PM
A static string does not exist on a class instance. In this case you have a PlayerStatus class instance on statusContainer.
To access mainStatus.. you would do something like this..
currentStatus = PlayerStatus.mainStatus;
But that won't work for your case, as it seems you want the value of mainStatus on a specific PlayerStatus gameObject instance.
So simply change your declaration to
public string mainStatus = "1";
I'd also suggest reading up on code formatting best practices. Public variables are usually in Capitals.
So
public string MainStatus = "1";
Your answer
![](https://koobas.hobune.stream/wayback/20220613074344im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Accessing another var on another script 1 Answer
Increasing a score value? 2 Answers
Reset a static variable? 1 Answer
Will static variables not work if negative? 1 Answer
Global Varible Problem 2 Answers