14
9

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 5 years have passed since last update.

【Unity】バックグラウンド動作時のキー入力取得

Posted at

Unityがバックグラウンドで動いているとき,Inputクラスではキー入力を取得できません。

そこで,以下のリンクにあるパッケージを利用します。
英語ですが,使い方もほぼ書いてあります。
https://github.com/Elringus/UnityRawInput

サンプルソース

using UnityEngine;
using UnityRawInput;

public class RawKeyInputTest : MonoBehaviour
{
	public bool WorkInBackground;
	public bool InterceptMessages;

	private void OnEnable ()
	{
		RawKeyInput.Start(WorkInBackground);
		RawKeyInput.OnKeyUp += LogKeyUp;
		RawKeyInput.OnKeyDown += LogKeyDown;

	}

	private void OnDisable ()
	{
		RawKeyInput.Stop();
		RawKeyInput.OnKeyUp -= LogKeyUp;
		RawKeyInput.OnKeyDown -= LogKeyDown;
	}

	private void OnValidate ()
	{
		RawKeyInput.InterceptMessages = InterceptMessages;
	}

	private void LogKeyUp (RawKey key)
	{
		Debug.Log("Key Up: " + key);
	}

	private void LogKeyDown (RawKey key)
	{
		Debug.Log("Key Down: " + key);

		//Aが押されたら
		if (RawKeyInput.IsKeyDown(RawKey.A)) {
			print ("test");
		}
	}


}

よく使うと思うのはこの部分


		//Aが押されたら
		if (RawKeyInput.IsKeyDown(RawKey.A)) {
			print ("test");
		}

ここで特定のキーの入力を取得できます。
RawKey.取得したいキー のように書き,あとはキー入力で行いたい処理を書けばOKです。

14
9
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
14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?