Javascript functions as variables?

Long story short, I will start with the code.

var u = Input.GetKey ("up");
var d = Input.GetKey ("down");
var l = Input.GetKey ("left");
var r = Input.GetKey ("right");
if (u) {
rigidbody2D.velocity = new Vector2 (0, moveSpeed);
}
if (d) {
rigidbody2D.velocity = new Vector2 (0, -moveSpeed);
}
if (r) {
rigidbody2D.velocity = new Vector2 (moveSpeed, 0);
}
if (l) {
rigidbody2D.velocity = new Vector2 (-moveSpeed, 0);
}	

Pretty simple, but the problem is in my game camera tends to rotate, so when camera is rotated for 90* the controlls are wrong, so I had an idea of with triggers to change u/d/r/l values to change, but when I try to change them with “If” statements, because of “var” code unity says, that u/d/l/r values doesnt exsist in current context, so i need
to save them globaly, so I tryed

Input u;
Input d;
Input l;
Input r;

u = Input.GetKey ("up");
d = Input.GetKey ("down");
l = Input.GetKey ("left");
r = Input.GetKey ("right");

But that doesnt work, does any one know how to save those values globaly? Liek bools, ints, strings, GameObjects and so on? But for the Input keys? Have been looking for hours.

To be honest, I’d recommend you just call the functions as-needed… but there is a nugget of programming knowledge to be learned, here, so I’ll answer the question in that vein.

As you noticed, there’s a problem with this:

var u = Input.GetKey ("up");

That just calls GetKey and stores the result. u is now a boolean.

Like many programming environments, UnityScript allows you to create function references, which are sometimes called “delegates”:

function Update () {
	var check = checkFunc;
	if (check()) {
		Debug.Log("Hey");
	}
}

function checkFunc() {
	return Input.GetKey("space");
}

Things to notice about the above example:

  • We create a checkFunc function which does what we need.
  • In our update function, we create a variable check with the value “checkFunc” (no parens). We can then call check() just as if it were a function, because it points to one.
  • A function name with parens will call the function; without parens is a function reference. Beginners sometimes find this confusing.

If you need to, you can even create delegates that take arguments, just like regular functions.

You can also create an “anonymous” delegate, which doesn’t have a name. These are sometimes called “lambda functions” or just “lambdas”. The syntax for this is esoteric:

function Update () {
	var check = function()(Input.GetKey("space"));
	if (check()) {
		Debug.Log("Hey");
	}
}