Search code examples
c#unityscriptunity-game-engine

How do i make Input.GetKey to be pressed once inside Update function?


If i'm using like now GetKeyDown instead KeyDown pressing the key "o" does nothing. But if i'm using GetKey and then KeyCode.O when i press on the O key the character stop walking but i need to keep pressing the O key all the time if i release the key the character will continue walking.

What i want to do is once when i click once on the key O the character will stop walking even when releasing the key and then if i click on the key "p" it will resume the walking.

The reason i'm using the speed property for pause/continue the walking is that if i will make:

gameObject.GetComponent<Animator> ().Stop(); 

The character stop walking but then the rest of the scene/world is moving to the character. And when i tried to use:

gameObject.GetComponent<Animator> ().Play();

Then i need to put some parameter in the Play like Play("Walk") but it didn't work.

That's why i decided to use the speed property for pause/continue.

using UnityEngine;
using System.Collections;

public class Ai : MonoBehaviour {

    Animator _anim;
    // Use this for initialization
    void Start () {

        _anim = GetComponent<Animator> ();
    }


    // Update is called once per frame
    void Update () {

        if (Input.GetKey (KeyCode.Z)) {
            _anim.speed = 20.0f;
        }

        if (Input.GetKeyDown ("o"))
            gameObject.GetComponent<Animator> ().speed = 0;
        if(Input.GetKeyDown("p"))
            gameObject.GetComponent<Animator>().speed = 2;
    }
}

Solution

  • Input.GetKeyX can only get keys that are specified under Edit > Project Settings > Input. You need to specify your key there if it does not match one of the existing ones.

    Just change one of the existing ones if you don't need it or change the size to create an extra on. The name of the axis is what you put into Input.GetKeyX, for example Input.GetKeyDown("Fire1").

    Edit:
    Some more indepth information in the docs: https://docs.unity3d.com/Manual/ConventionalGameInput.html