- Home /
Problem with accessing static variables
Hi. I'm using a GameObject called References, containing a script with the same name, which contains references to other GameObjects which are activated and deactivated during gameplay. Now, I'm having problems with referencing the static variables within the References script. The error I get is:
Assets/Scripts/CharacterSelection.cs(43,87): error CS0176: Static member `References.playerRef' cannot be accessed with an instance reference, qualify it with a type name instead
and the erratic code looks like so:
private GameObject playerRef;
void Start () {
playerRef = GameObject.Find ("References").GetComponent<References>().playerRef;
}
The References script looks like this (the value of the variable is assigned elsewhere):
public static GameObject playerRef;
I've been googling for help on static variables, but all I can find is how to work with static methods. If anybody could give me a pointer on what I'm doing wrong, it would be really helpful.
Here's the script which produces the error: https://github.com/choiie/AmpersandLime/blob/master/Assets/Scripts/CharacterSelection.cs
Answer by Bunnybomb7670 · Jun 19, 2014 at 10:58 PM
Ok so, instead of finding an Instance, you can refer straight to the class itself. so you would do References.playerRef; Static variables are on their own, a single instance and the way you access them is by referring to the base class, rather than finding an instance of the class within the scene. They are help separately outside of instances.
http://www.dotnetperls.com/global-variable might help a bit more with this issue.
So if I'd simply write References.playerRef I would get the variable in the References script? Will it automatically deter$$anonymous$$e where to find the References script?
Ok, so that worked - I read somewhere that to access variables in other scripts they need to be made static, but your solution worked fine.
To access variables in other scripts they do not need to be static, as long as you have a reference to their gameObject in the world, you can use getComponent to access that specific script then retrieve that instance variable, without it being static. Static means only one, which is not always good, something such as a zombie enemy cannot have a static Health because when one is damaged, all of them would be damaged.