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.

1 Answer

1

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 :slight_smile:

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. Assuming 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.