5.

Unity でキーボード入力を受け取る方法完全ガイド

編集
この記事の要点
  • Unity のキーボード入力Old Input Manager新 Input System Package の 2 系統
  • Old: Input.GetKey(KeyCode.W) / Input.GetKeyDown / Input.GetAxis("Horizontal")
  • New: UnityEngine.InputSystem + Input Action Asset、コールバック方式で複数デバイス対応
  • Update() で入力検出、FixedUpdate() で物理処理 (Rigidbody)。Update で入力を保存し FixedUpdate で使う
  • Unity 2022+ は 新 Input System を推奨。クロスプラットフォーム / キーバインド変更 / コントローラ対応が容易

Old Input Manager の基本

Unity 標準搭載 (Project Settings → Player → Active Input Handling で切り替え可能)。最も簡単なキーボード入力取得方法:

using UnityEngine;

public class PlayerInput : MonoBehaviour
{
    void Update()
    {
        // 押されている間 true
        if (Input.GetKey(KeyCode.W))
        {
            Debug.Log("W キー押下中");
        }

        // 押された瞬間だけ true (1 フレームだけ)
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("ジャンプ!");
        }

        // 離された瞬間だけ true
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Debug.Log("ジャンプキー離した");
        }

        // 修飾キー併用
        if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.W))
        {
            Debug.Log("Shift + W ダッシュ");
        }
    }
}

KeyCode 一覧

カテゴリKeyCode
アルファベットKeyCode.AKeyCode.Z
数字KeyCode.Alpha0KeyCode.Alpha9 (上段)、KeyCode.Keypad0 〜 (テンキー)
矢印KeyCode.UpArrow / DownArrow / LeftArrow / RightArrow
修飾KeyCode.LeftShift / RightShift / LeftControl / LeftAlt / LeftCommand
スペース等KeyCode.Space / Return / Escape / Tab / Backspace
ファンクションKeyCode.F1KeyCode.F15
マウスKeyCode.Mouse0Mouse6

Input.GetAxis: 軸入力 (移動)

キーボード上下左右 や WASD を「-1.0 〜 +1.0」の浮動小数で取得できます。スムージング付き:

public class PlayerMover : MonoBehaviour
{
    public float speed = 5f;

    void Update()
    {
        // Project Settings → Input Manager で定義済の軸
        float h = Input.GetAxis("Horizontal"); // A/D, ←/→
        float v = Input.GetAxis("Vertical");   // W/S, ↑/↓

        // GetAxisRaw はスムージング無し (-1, 0, 1 のみ)
        float hRaw = Input.GetAxisRaw("Horizontal");

        Vector3 move = new Vector3(h, 0, v) * speed * Time.deltaTime;
        transform.Translate(move);
    }
}

Update vs FixedUpdate

入力検出は Update() で、物理オブジェクト (Rigidbody) の操作は FixedUpdate() で行うのが鉄則です:

public class PhysicsMover : MonoBehaviour
{
    private Rigidbody rb;
    private bool jumpRequested = false;
    private Vector3 moveInput;

    void Start()
    {
        rb = GetComponent();
    }

    void Update()
    {
        // ★ 入力は Update で (取りこぼし防止)
        moveInput = new Vector3(
            Input.GetAxisRaw("Horizontal"),
            0,
            Input.GetAxisRaw("Vertical")
        );

        if (Input.GetKeyDown(KeyCode.Space))
            jumpRequested = true;   // フラグだけ立てる
    }

    void FixedUpdate()
    {
        // ★ 物理処理は FixedUpdate で
        rb.MovePosition(rb.position + moveInput * 5f * Time.fixedDeltaTime);

        if (jumpRequested)
        {
            rb.AddForce(Vector3.up * 5f, ForceMode.Impulse);
            jumpRequested = false;
        }
    }
}

新 Input System (推奨)

Unity 2019.1+ で Package Manager からインストール可能。Unity 2022.3 LTS 以降は標準的な選択肢です。

# インストール手順
# 1. Window → Package Manager → Unity Registry
# 2. "Input System" を選択 → Install
# 3. Project Settings → Player → Active Input Handling
#    → "Input System Package (New)" または "Both"
# 4. Unity 再起動

方式 A: 直接呼び出し (Keyboard.current)

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerNew : MonoBehaviour
{
    void Update()
    {
        // 現在のキーボード
        var kb = Keyboard.current;
        if (kb == null) return;

        if (kb.wKey.isPressed)
            Debug.Log("W 押下中");

        if (kb.spaceKey.wasPressedThisFrame)
            Debug.Log("Space 押された瞬間");

        if (kb.escapeKey.wasReleasedThisFrame)
            Debug.Log("Esc 離した");
    }
}

方式 B: Input Action Asset (推奨)

Project ウィンドウで Create → Input Actions → 「PlayerControls」 を作成。エディタでアクションを定義し、コードからは抽象的に呼び出します:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerActionBased : MonoBehaviour
{
    public InputActionAsset actions;
    private InputAction moveAction;
    private InputAction jumpAction;

    void OnEnable()
    {
        moveAction = actions.FindAction("Move");
        jumpAction = actions.FindAction("Jump");

        jumpAction.performed += OnJump;

        moveAction.Enable();
        jumpAction.Enable();
    }

    void OnDisable()
    {
        jumpAction.performed -= OnJump;
        moveAction.Disable();
        jumpAction.Disable();
    }

    void Update()
    {
        Vector2 m = moveAction.ReadValue();
        transform.Translate(new Vector3(m.x, 0, m.y) * Time.deltaTime * 5f);
    }

    private void OnJump(InputAction.CallbackContext ctx)
    {
        Debug.Log("Jump triggered!");
    }
}

Old vs New Input System

項目Old Input ManagerNew Input System
呼び出しInput.GetKey(KeyCode.W)Keyboard.current.wKey.isPressed / Action
キーバインド変更面倒 (要再起動)ランタイム変更可
コントローラ対応限定的多様な機種に対応
マルチプレイヤー困難PlayerInputManager で容易
イベント駆動×○ (callbacks)
学習コスト
推奨度レガシー / 互換用途新規プロジェクト

SendMessage 方式 (PlayerInput コンポーネント)

// GameObject に PlayerInput コンポーネントを付与し
// "Behavior" を "Send Messages" に設定すると
// 命名規則でメソッドが自動呼び出しされる

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerSendMessage : MonoBehaviour
{
    public void OnMove(InputValue value)
    {
        Vector2 v = value.Get();
        Debug.Log($"Move: {v}");
    }

    public void OnJump()
    {
        Debug.Log("Jump");
    }

    public void OnFire(InputValue value)
    {
        if (value.isPressed) Debug.Log("Fire pressed");
    }
}

FAQ

Q: Input.GetKeyDown が反応しない
A: FixedUpdate に書いていないか確認 (1 フレーム入力は Update でしか捕捉できない)。または新 Input System に切り替え済で Old を呼んでいるとエラー。

Q: 日本語キーボード固有のキー
A: KeyCode に半角全角等は無いが、新 Input System なら Keyboard.current.imeSelected 等が利用可能。

Q: 複数プレイヤーで別キーボード対応
A: 新 Input System の PlayerInputManager + Player Input Action Asset を使う。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. スクリプトの作成と実行
  2. C# のクラス一覧
  3. シーンの移動方法
  4. オブジェクトの移動・回転
  5. キーボードの入力値を受け取る
  6. オブジェクトの取得とコンポーネントの取得
  7. 衝突時の処理
  8. Webページを開く
  9. コンポーネントの取得
  10. 処理を一定時間待つ
  11. コンソールへのログ出力方法
  12. 飛行機の加速と減速
  13. ジェットエンジンのエフェクトとオーディオ