Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I need to know how to bind keys to actions through Javascript within Unity.

When I develop web applications, I normally use this:

var KeyBind = function() {
    if (document.addEventListener) {
        document.addEventListener("keydown", keyDownHandler, false);
        document.addEventListener("keydown", keyUpHandler, false);
    }
    else if (document.attachEvent) {
        document.attachEvent("onkeydown", function() {
            keyDownHandler(window.event);
        });
        document.attachEvent("onkeydown", function() {
            keyUpHandler(window.event);
        });
    }

    function keyDownHandler(e) {
        var key = e.which || e.keyCode;
        if (key == "27") {
            window.location="file:///D:/Users/pferris/Documents/Unnamed%20Site%202/HordeAttack.html";            
        };
};

Does Unity use a similar method, or will I have to do something completely different?

I've been through the help section a bit, but nothing seemed very satisfactory.

share|improve this question
    
This is less urgent but it would be nice if people could tell me how best to deal with the workflow of our company (Me and my friends are developing a game) since the lead programmer can't be persuaded to do anything. I'm the lead artist, so this sort of thing is waaaaaaaay beyond what I would normally do. –  Paul Ferris Jan 25 '13 at 5:00
add comment

1 Answer

A similar method would be from the Input class

http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKeyDown.html

function Update () {
    if (Input.GetKeyDown (KeyCode.Space))
        print ("space key was pressed");
}
share|improve this answer
    
Is there an issue with where this goes? I tried placing it in scripts for some of my assets (terrain and a camera), but nothing happened when I tested it. –  Paul Ferris Jan 25 '13 at 8:20
    
@PaulFerris it needs to go in an Update or FixedUpdate method on some object so that it gets called every frame. –  Tetrad Jan 25 '13 at 17:13
    
I did that, though. It's running from within an Update method, but nothing is displayed in the console when I test it. –  Paul Ferris Jan 26 '13 at 4:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.