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?

【Unity】旧 Input のやり方で Input System を使いたい

Posted at

導入

少し前に出た「Input System」、時間が経って段々とメジャーになりつつあります。
Unreal Engine にも Enhanced Input というものがあるので、最近のゲーム開発では一般的になってきている考え方っぽいですね。

それで、 Unity の Input System はイベント駆動型になっています。
つまり、入力された時に発火する処理を登録する感じです。

// このメソッドを登録しておいて、クリック時に呼び出してもらう
private void OnClick()
{
}

これまでの Unity だと Input.GetKey... みたいに入力値を取得する感じだったので、結構使い勝手が変わっていますね。
そういうわけで、「無理やり旧方式でも出来るようにしよう!」ということをやってみました。

▼▼▼ GitHub ▼▼▼
サンプルがダウンロードできます

概要

下準備として、いつも通り以下のことをやります。

  1. Input Action を作成して入力を定義する
  2. C#クラスを Generate する

そして、今回作成した InputManager は、このC#クラスを更にラッパーするクラスです。
RuntimeInitializeLoadType.SubsystemRegistration で初期化とコールバック登録を行い、
InputSystem.onBeforeUpdate で入力値のリセットを (必要ならば) 行います。
意外とこれだけです。

使い方

ダウンロードできるサンプルコードから、一部を抜粋します。

入力の登録

InputInfo 型のメンバを宣言し、 Input Action でのパスと入力の種類を指定してインスタンス化します。

internal static partial class InputManager
{
    internal static InputInfo Click { get; private set; }
    internal static InputInfo Hold { get; private set; }
    internal static InputInfo Value0 { get; private set; }
    internal static InputInfo Value1 { get; private set; }
    internal static InputInfo Value2 { get; private set; }
    internal static InputInfo Value3 { get; private set; }

    private static void Bind()
    {
        Click = Create(source.Main.Click, InputType.Click);
        Hold = Create(source.Main.Hold, InputType.Hold);
        Value0 = Create(source.Main.Value0, InputType.Value0);
        Value1 = Create(source.Main.Value1, InputType.Value1);
        Value2 = Create(source.Main.Value2, InputType.Value2);
        Value3 = Create(source.Main.Value3, InputType.Value3);
    }
}

入力の取得

InputInfo のメンバにアクセスします。
入力の種類によって異なるメンバから読み取ります。
ジェネリックを使うことも考えましたが、記述量が多くなるのでやめました。

bool inputClick = InputManager.Click.Bool;
bool inputHold = InputManager.Hold.Bool;
bool inputValue0 = InputManager.Value0.Bool;
float inputValue1 = InputManager.Value1.Float;
UnityEngine.Vector2 inputValue2 = InputManager.Value2.Vector2;
UnityEngine.Vector3 inputValue3 = InputManager.Value3.Vector3;

締め

アンチパターンな気はしますが、こっちの方が使いやすいので色々なところで使っています。
技術が進歩するにつれて、色々なことが複雑になっていますね。
個人的にはもっとシンプルでいい気がするのですが…。

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?