0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity 入力されたキー名を取得する方法

Posted at

##0.0 はじめに
方向キーなどキーボード上のキーによってゲームを進行させたいときがあります。
その際に有効となる、入力されたキーの情報を取得する方法を紹介します。

##1.0 Inputクラスをからキー情報を取得する方法
Input.inputStringにて現在のフレームで入力されたキーの名前を取得できます。
アルファベットや数字を取得するにはこれが一番簡単な方法ですが、スペースキーや特殊なキーの情報は取得できません。

KeyTest.cs
    // 何かキーが押された場合
    if (Input.anyKeyDown) {
        string keyStr = Input.inputString; // 入力されたキーの名前を取得
        Debug.Log(keyStr + " のボタンが押されたよ!!"); // コンソールに表示
    }

##2.0 KeyCodeからキー情報を取得する方法
KeyCodeに登録されているキーから検索して情報を確認する方法です。
Ctrlキーなどでは左側、右側の区別もあります。より細かく取得したい場合に使用できます。
foreachで入力されたキーのコードとすべてのキーコードを比較して一致したものをcodeに取り出しています。

KeyTest.cs
    // 何かキーが押された場合
    if (Input.anyKeyDown) {
        foreach(KeyCode code in Enum.GetValues(typeof(KeyCode))) { // 検索
            if (Input.GetKeyDown(code)) { // 入力されたキーの名前と一致した場合
                Debug.Log(code.ToString() + " のボタンが押されたよ!!"); // コンソールに表示
            }
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?