Keycode
をキーに使用し、値として機能(Action
)を使用します。 Start
関数内のそれぞれのパラメータを持つ関数を追加します。これはif
またはswitch
ステートメントのすべてに乗ります。
Dictionary<KeyCode, System.Action> keyCodeDic = new Dictionary<KeyCode, System.Action>();
アルファKeycode
列挙型は48
から始まり、57
で終了。 Start
関数で
Alpha0 = 48,
Alpha1 = 49,
Alpha2 = 50,
Alpha3 = 51,
Alpha4 = 52,
Alpha5 = 53,
Alpha6 = 54,
Alpha7 = 55,
Alpha8 = 56,
Alpha9 = 57,
、48
から57
のループはKeycode
にループから各int
値をキャスト。各ループのをDictionary
に追加します。また、関数パラメータとして使用する一時変数を用意してください。この変数は0
から始まり、各ループの後に増分されます。これは、キーボード上のアルファキーが0
(Alpha0)から始まるので、0から開始する必要があります:Dictionary
を通じてUpdate
機能ループで、
int paramValue = 0;
for (int i = 48; i <= 57; i++)
{
KeyCode tempKeyCode = (KeyCode)i;
//Use temp variable to prevent it from being capture
int temParam = paramValue;
keyCodeDic.Add(tempKeyCode,() => MethodCall(temParam));
paramValue++;
}
最後にして、押されてからのキーは、対応する関数を呼び出すかどうかを確認していますそのキーの値はDictionary
です。ここで
//Loop through the Dictionary and check if the Registered Keycode is pressed
foreach (KeyValuePair<KeyCode, System.Action> entry in keyCodeDic)
{
//Check if the keycode is pressed
if (Input.GetKeyDown(entry.Key))
{
//Check if the key pressed exist in the dictionary key
if (keyCodeDic.ContainsKey(entry.Key))
{
//Debug.Log("Pressed" + entry.Key);
//Call the function stored in the Dictionary's value
keyCodeDic[entry.Key].Invoke();
}
}
}
全体のことをどのように見えるかです:私は私の1,2または3またはNを返します方法 `int型GetKeyPressed(..)を作成します`
Dictionary<KeyCode, System.Action> keyCodeDic = new Dictionary<KeyCode, System.Action>();
void Start()
{
//Register Keycodes to to match each function to call
const int alphaStart = 48;
const int alphaEnd = 57;
int paramValue = 0;
for (int i = alphaStart; i <= alphaEnd; i++)
{
KeyCode tempKeyCode = (KeyCode)i;
//Use temp variable to prevent it from being capture
int temParam = paramValue;
keyCodeDic.Add(tempKeyCode,() => MethodCall(temParam));
paramValue++;
}
}
void MethodCall(int keyNum)
{
Debug.Log("Pressed: " + keyNum);
}
void Update()
{
//Loop through the Dictionary and check if the Registered Keycode is pressed
foreach (KeyValuePair<KeyCode, System.Action> entry in keyCodeDic)
{
//Check if the keycode is pressed
if (Input.GetKeyDown(entry.Key))
{
//Check if the key pressed exist in the dictionary key
if (keyCodeDic.ContainsKey(entry.Key))
{
//Debug.Log("Pressed" + entry.Key);
//Call the function stored in the Dictionary's value
keyCodeDic[entry.Key].Invoke();
}
}
}
}
内部に 'switch..case'ステートメントの長いセットを入れることができます。 – FortyTwo