こちらにキーコンフィグの作り方があったので、参考にさせていただきました。
http://ch.nicovideo.jp/isemito/blomaga/ar427493
やりたいこと
- 押したパッドの値が返ってくるようにしたい
- 連続で押していったら押した順番に返って来てほしい
なのでボタンが押されたときにコールバックするような仕組みにしたら簡単そう。
using System;
using UnityEngine;
using System.Collections;
public class KeyConfigure : MonoBehaviour
{
private event Action<KeyCode> keyDown;
public void StartKeyConfigure (Action<KeyCode> onKeyDownDelgate)
{
keyDown += onKeyDownDelgate;
StartCoroutine ("CheckAllKeyDown");
}
public void StopKeyConfigure ()
{
StopCoroutine ("CheckAllKeyDown");
keyDown = null;
}
IEnumerator CheckAllKeyDown ()
{
while (true) {
while (!Input.anyKeyDown) yield return new WaitForSeconds (0.01F);
foreach (KeyCode code in Enum.GetValues(typeof(KeyCode))) {
if (Input.GetKeyDown (code)) { keyDown (code); break; }
}
yield return new WaitForSeconds (0.01F);
}
}
}
使うときは例えばこんな感じで
using UnityEngine;
using System.Collections;
using System.Linq;
public class GamePadManager : MonoBehaviour
{
public KeyCode[] codes;
private int count;
public KeyConfigure confidure;
// Use this for initialization
void Start ()
{
confidure.StartKeyConfigure (OnKeyDown);
}
// Update is called once per frame
void Update ()
{
}
void OnKeyDown (KeyCode code)
{
if (codes.Contains (code)) {
print ("already exists");
return;
}
codes [count++] = code;
print (code);
if (count >= codes.Length) confidure.StopKeyConfigure ();
}
}
上記のGamePadManagerを実行すると、以下のような流れになります
-
confidure.StartKeyConfigure (OnKeyDown);
でキー入力を受け付ける状態になる - キーを押すと
OnKeyDown (KeyCode code)
が呼ばれて、codesに押したキーが入っていく(重複したら入れない) - キーの数が配列の長さを超えたら
confidure.StopKeyConfigure ();
でキー入力の受付を終了する
これでゲームでよくある「上から順番にキーを設定していく」画面は作れそう。
課題
KeyCode
列挙体にはスティックの値は設定されていない。
つまりゲームパッドの十字キーとかスティックの入力はこの実装では取ることができない。
こちらは Input.GetAxis
でしか取れないっぽいので、InputManagerであらかじめ用意しておくとかそんなんしかなさそう。
いい方法ご存知のから教えてください。