Operating with the Keyboard (Input System Package Version)

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2020.3.25f1
Input System Package
  • 1.2.0

Prerequisites for this tip

The following settings have been made in advance as a premise for the description of this tip.

Determine the moment a specific key is pressed

When you press a key, try to move the object. Place a text object in the Canvas to confirm the move. The size and position can be appropriate.

Keyboard handling is done by scripts. KeyboardOneFrame In this case, we create it as .

The code looks like this:

using UnityEngine;
using UnityEngine.UI;           // 追加
using UnityEngine.InputSystem;  // 追加

public class KeyboardOneFrame : MonoBehaviour
{
  /// <summary>移動させるテキストオブジェクト。</summary>
  [SerializeField] private Text TextObject;

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    if (TextObject == null)
    {
      Debug.Log($"{nameof(TextObject)} が null です。");
      return;
    }

    // キーボードの情報を取得
    var keyboard = Keyboard.current;
    if (keyboard == null)
    {
      Debug.Log("キーボードがありません。");
      return;
    }

    var transform = TextObject.transform;

    // wasPressedThisFrame は押した瞬間のみ true となる
    // キーは「keyboard[Key.RightArrow]」のような指定の仕方もある
    if (keyboard.leftArrowKey.wasPressedThisFrame)
    {
      transform.Translate(-1, 0, 0);
    }
    if (keyboard.rightArrowKey.wasPressedThisFrame)
    {
      transform.Translate(1, 0, 0);
    }
    if (keyboard.upArrowKey.wasPressedThisFrame)
    {
      transform.Translate(0, 1, 0);
    }
    if (keyboard.downArrowKey.wasPressedThisFrame)
    {
      transform.Translate(0, -1, 0);
    }
  }
}

Keyboard.current You can get the current keyboard key press status etc. from . keyboard.xxxxxxx.wasPressedThisFrame returns only true the timing of the moment the key is pressed. In this code, the moment the cursor key is pressed, the Move operation is performed on the Text object transform . Since it is processed only at the moment of pressing, the movement does not continue even if the key is pressed.

After EventSystem saving the script, attach to the object KeyboardOneFrame and click Set the text object to be moved to the Text object.

Try running the game and checking if the @ mark moves when you press the cursor key. Also, make sure that holding down the key does not move the @ symbol.

What types of keys can be determined?

It is written on the official website, so please check there.

Determine the moment a specific key is released

We do not create a sample, but the moment wasPressedThisFrame you press it is determined by the property, while the moment wasReleasedThisFrame you release it can be judged by .

Determine while pressing a specific key

This is also determined by the script. You can add it to the previous code, but this time we will create a new script file called and write it KeyboardPress .

The script looks like this:

using UnityEngine;
using UnityEngine.UI;           // 追加
using UnityEngine.InputSystem;  // 追加

public class KeyboardPress : MonoBehaviour
{
  /// <summary>回転させるテキストオブジェクト。</summary>
  [SerializeField] private Text TextObject;

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    if (TextObject == null)
    {
      Debug.Log($"{nameof(TextObject)} が null です。");
      return;
    }

    // キーボードの情報を取得
    var keyboard = Keyboard.current;
    if (keyboard == null)
    {
      Debug.Log("キーボードがありません。");
      return;
    }

    var transform = TextObject.transform;

    // isPressed は押している間はずっと true となる
    // キーは「Keyboard.current[Key.Space]」のような指定の仕方もある
    if (keyboard.spaceKey.isPressed)
    {
      transform.Rotate(0, 0, 1);
    }
  }
}

While the spacebar is pressed, the text object is rotated. keyboard.xxxxxxxx.isPressed returns for the entire true duration of the key.

Attach the EventSystem saved script to Text Object and set the text object to be rotated.

Make sure the @ symbol rotates all the way while the game is running and holding the spacebar.

Get all pressed keys

Try to display all the keys you are pressing as text. You have placed a text object to display the key you are pressing.

KeyboardAllKeys Create a script with the name .

The script looks like this:

using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;  // 追加
using UnityEngine.UI;           // 追加

public class KeyboardAllKeys : MonoBehaviour
{
  /// <summary>移動させるテキストオブジェクト。</summary>
  [SerializeField] private Text TextObject;

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    if (TextObject == null)
    {
      Debug.Log($"{nameof(TextObject)} が null です。");
      return;
    }

    // キーボードの情報を取得
    var keyboard = Keyboard.current;
    if (keyboard == null)
    {
      Debug.Log("キーボードがありません。");
      TextObject.text = "";
      return;
    }

    // allKeys からすべてのキーの情報を走査し isPressed で押しているキーのみを抽出する
    TextObject.text = string.Join(", ", keyboard.allKeys.Where(x => x.isPressed).Select(x => x.keyCode.ToString()));
  }
}

keyboard.allKeys allows you to get information about all keys. You can extract only those that are true from isPressed those keys and retrieve only the keys you are pressing. After that, the key you are pressing is converted into a string and displayed as text.

The EventSystem created script attaches to and sets a text object for displaying the pressing key.

Run the game and verify that the key you are pressing appears.

By the way, even if you press a lot of keys, all the keys may not be displayed, but don't worry about it because it is a physical problem due to keyboard wiring.

Get typed characters

Until now, you got the type of key you pressed, but it's also possible to get the characters you actually typed. For example, if the "A" key is pressed, the letter "a" can be obtained, and if the "Shift+A" key is pressed, the letter "A" can be obtained. If the IME is enabled, you may also be able to retrieve Japanese.

However, these entered characters cannot be retrieved in properties and will be acquired in the form of events.

In the sample, a text object is placed to display the entered characters.

Create a script. KeyboardTextInput The name is .

Enter the script as follows:

using UnityEngine;
using UnityEngine.InputSystem;  // 追加
using UnityEngine.UI;           // 追加

public class KeyboardTextInput : MonoBehaviour
{
  /// <summary>移動させるテキストオブジェクト。</summary>
  [SerializeField] private Text TextObject;

  /// <summary>
  /// オブジェクトが有効になったときに呼ばれるイベント。
  /// </summary>
  public void OnEnable()
  {
    // 文字が入力されたときに呼ばれるイベントをセット
    Keyboard.current.onTextInput += OnTextInput;
  }

  /// <summary>
  /// オブジェクトが無効になったときに呼ばれるイベント。
  /// </summary>
  public void OnDisable()
  {
    // 文字が入力されたときに呼ばれるイベントを解除
    Keyboard.current.onTextInput -= OnTextInput;
  }

  /// <summary>
  /// 文字を入力するたびに呼ばれる。
  /// </summary>
  /// <param name="c">入力された文字。</param>
  public void OnTextInput(char c)
  {
    TextObject.text += c;
  }
}

KeyboardThe onTextInput class has an event called , which is called whenever text is entered. OnEnable Here, the method is registered at the timing of andOnDisable canceled at OnTextInput OnTextInput the timing of . Keyboard.current is a unique object that exists from the time the game is executed until it is terminated, so OnDisable be sure to release it at the timing of . If you can always pair event registration and cancellation, you can set it at any other time.

OnTextInput In the method, the entered character is set as an argument c , so it is appended as text.

After EventSystem saving the script, attach it to and set a text object for display.

Try running the game and pressing the key. You should see the characters entered. If you press it at the same time as the Shift key, you should be able to enter capital letters and symbols. You can also enter Japanese if the IME is enabled. On the other hand, if you press a non-character key such as the cursor key, nothing will happen.