Unity6からは、キー入力を受け取るシステムとして、Input.GetMouseButton(0)
のような旧来のInput Managerに代わりInput Systemが使用されるようになりました。
引き続き Input Manager を使うには、
ProjectSettings>Player>OtherSettings>ActiveInputHandringでBothを選択します。
ただこれをすると、Inputは拾ってくれるものの、数百ミリ秒レベルで遅延が発生しているように感じます(Unity6000.1.8現在)。
InputSystemは、基本的には旧来のようにUpdate()内で毎回調べて使用するのではなく、キーが押された/離されたなど値が変わったときにイベントが呼ばれるものになっています。
これによって、複雑な状況にもすっきり記述できるようになった反面、単純なキー操作を調べたい場合には若干面倒が増えることになります。
そこで、ひとまず新InputSystemも旧来のInputManagerと同じようにUpdate()で調べられるようにしてみます。
- キー入力で動かしたいGameObjectを作成、AddComponent>PlayerInputでPlayerInputを追加します
ここでは移動したことがわかりやすいように、SpriteをもつObjectにPlayerInputを追加しています。
-
Inspector>生成したPlayerInput>Actions をクリックするとProjectで当該のInputSystems_Actions が選択されます
-
Project>InputSystem_Actions を選択>Inspectorで
Generate C#
にチェックを入れ[Apply]ボタンを押します。すると InputSystem_Actions.cs (InputSystem_Actionsと同じ名前)というスクリプトファイルが生成されます
- .csスクリプトファイルが作成されたら、Project>Create>MonobehaviourScriptでMyPlCtrl.csという名前のファイルを生成します
- 生成したMyPlCtrl.csファイルをダブルクリックで開き、中身を以下のように書き換えます
MyPLCtrl.cs
namespace MyGame
{
using UnityEngine;
using UnityEngine.InputSystem;
public class MyPLCtrl : MonoBehaviour
{
[SerializeField, Range(1, 10)] float m_speed = 5.0f;
InputSystem_Actions m_actions;
InputSystem_Actions.PlayerActions m_player;
private void Awake()
{
m_actions = new InputSystem_Actions();
m_player = m_actions.Player;
//m_Player.Move.performed += OnMove; // Subscribe to the Move action
//m_Player.Move.canceled += OnMove; // Subscribe to the Move action
}
private void OnEnable() => m_actions.Enable(); // Enable the input actions
private void OnDisable() => m_actions.Disable(); // Disable the input actions to prevent them from being active when not needed
private void OnDestroy() => m_actions.Dispose(); // Clean up the input actions
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 moveInp = m_player.Move.ReadValue<Vector2>();
transform.Translate(moveInp * m_speed * Time.deltaTime, Space.World);
if (moveInp != Vector2.zero)
{
Debug.Log("Move Vector: " + moveInp.ToString());
}
}
}
}
Awake()内、m_actions = new InputSystem_Actions();
の部分は、```Generate C#``で生成されたファイル名と同じにします。
- 中身を書き換えたら、
MyPlCtrl.cs
をPlayerInput
をもつObjectにアタッチします
Update()
内で値を取得するには、
Vector2 moveInp = m_player.Move.ReadValue<Vector2>();
のように、InputSystem_Actions
内で定義された名前を使用します。
- 設定を変更したい/追加したい場合はInputSystem_ActionsをCtrl+Dで複製し、そちらを改変します
または、Ctrate>InputActionsで新規のInputActionsファイルを生成し、空の状態からすべての設定を定義することも可能です。
その場合は、MyPLCtrl.cs
内
m_actions = new InputSystem_Actions();
の部分も合わせて変更します。