- Home /
Casting Variables
Hi
How would I go about casting some variables so they would be accessible to other scripts without having to define them once again.
Ex: var key1 = Input.GetKeyDown(KeyCode.Alpha1);
I want key1 to be known on all the scripts that use its name, is it even possible?
Thanks.
Answer by ArkaneX · Nov 18, 2013 at 03:24 PM
You have to declare class wide variable instead of variable declared inside method (e.g. Update).
JS:
var key1 : boolean;
function Update()
{
key1 = Input.GetKeyDown(KeyCode.Alpha1);
}
C#:
public bool key1;
void Update()
{
key1 = Input.GetKeyDown(KeyCode.Alpha1);
}
EDIT: although, I have to admit, result of Input.GetKeyDown
is probably not a best example :)
Well,thats not what I mean, What I mean is: I have defined in a script var x = 2; , then i want to go into another script and just if x==2 then do that, all without having to copy/define.
I'm afraid without a bit of code it is not possible. You have to somehow access the variable from another script. Assu$$anonymous$$g both scripts are attached to the same game object, you can do (C# version only):
private OtherScript _otherScript;
public int ValueInOtherScript
{
get { return _otherScript.value; }
}
void Awake()
{
_otherScript = GetComponent<OtherScript>();
}
void Update()
{
if (ValueInOtherScript == 2)
{
// do something
}
}
But I don't know if that's what you need...
You can make the value static
if you're using C#, and if you also make it public, you can access it from anywhere without having to have that object instantiated.
static doesn't have anything to do with C#, but you shouldn't use it if you don't know what it does. Namely, it means there can only be a single instance, so if you have two scripts with a static variable, it will always share the same value.
Ok,thanks for answers, I see that it is not quite possible.
Your answer
![](https://koobas.hobune.stream/wayback/20220613122136im_/https://answers.unity.com/themes/thub/images/avi.jpg)