- Home /
Access static variable c#
I have a c# script, with a static variable inside, that I would like to access, from another c# script but I cant figure out how. I was kind of thinking, if it was just like in Javascript, where you can do it like this.
var targetScript : Script;
function OnGUI () {
if (GUI.button(Rect(100,100,100,100),"Test")){
targetScript.number + 10;
}
}
But how would i do this in c#?
Answer by 8Eye · Oct 18, 2014 at 01:17 AM
you need to set the variable first
public static int number;
This is how you access it in another script
void Start(){
TheOtherScript.number = 10;
}
Thank you very much, but now I get this error, "Static class CurrencyScript' cannot derive from type
UnityEngine.$$anonymous$$onoBehaviour'. Static classes must derive from object" and I can't seem to figure out what is wrong.
I will try and make it clearer to you about using a static variable.
Here is the first script.
public class script1 : $$anonymous$$onoBehaviour {
public static int number;
}
Now here is the other script that you needs to access script 1
public class Script2 : $$anonymous$$onoBehaviour {
void Start(){
script1.number = 10;
}
}
If you want to access another script entirely you should do this
public class Script2 : $$anonymous$$onoBehaviour {
public Script1 script1; //Assign what script you need in the inspector and make sure it is of type "Script1"
void Start(){
script1.number = 10;
script1.word = "hello";
script1.transform = this.transform;
}
}
Thank you so much. I searched a lot and you are the only one that explained exactly what I want to do (use the static variables on another object).
Oh sorry, I meant is how to reference the public static class, and I already found that solution. int value = AnotherScipt.instance.variable;