キーボード
ユニティ
Aキーを押したときにログにAキーを押したと出るプログラムがあります。
if (Input.GetKeyDown(KeyCode.A))
{Debug.Log("Aキーを押した!");}
これが
if(押す.A)
{Debug.Log("Aキーを押した!");}
と書けるようになるプログラム
ちなみに押しているときは 入力.A
離したときは 離す.Aと書くことができる。
AからZのほかに
スペース、エンター、上、下、 左、 右
左クリック、 右クリック、 中クリックが使える
ボタン押しプログラム
ユニティの左の物体ウィンドウで欄の一番上に物体を作って、その物体にこのプログラムをくっつけます。
ユニティは基本的に欄の上の物体から順番にプログラムを実行します。なので欄の一番上の物体にプログラムをつける必要があります。
using System.Collections.Generic;
using UnityEngine;
public class キーボード : MonoBehaviour
{
void Start()
{キー入力.初期化();}
void Update()
{キー入力.更新();}
}
public static class 押す
{
public static bool A, B, C, D, E, F, G, H, I, J,
K, L, M, N, O, P, Q, R, S, T,
U, V, W, X, Y, Z;
public static bool スペース, エンター;
public static bool 上, 下, 左, 右;
public static bool 左クリック, 右クリック, 中クリック;
public static bool ホイール上, ホイール下;
}
public static class 入力
{
public static bool A, B, C, D, E, F, G, H, I, J,
K, L, M, N, O, P, Q, R, S, T,
U, V, W, X, Y, Z;
public static bool スペース, エンター;
public static bool 上, 下, 左, 右;
public static bool 左クリック, 右クリック, 中クリック;
}
public static class 離す
{
public static bool A, B, C, D, E, F, G, H, I, J,
K, L, M, N, O, P, Q, R, S, T,
U, V, W, X, Y, Z;
public static bool スペース, エンター;
public static bool 上, 下, 左, 右;
public static bool 左クリック, 右クリック, 中クリック;
}
public static class キー入力
{
static Dictionary<string, KeyCode> 対応表 = new Dictionary<string, KeyCode>()
{
{"A", KeyCode.A}, {"B", KeyCode.B}, {"C", KeyCode.C}, {"D", KeyCode.D},
{"E", KeyCode.E}, {"F", KeyCode.F}, {"G", KeyCode.G}, {"H", KeyCode.H},
{"I", KeyCode.I}, {"J", KeyCode.J}, {"K", KeyCode.K}, {"L", KeyCode.L},
{"M", KeyCode.M}, {"N", KeyCode.N}, {"O", KeyCode.O}, {"P", KeyCode.P},
{"Q", KeyCode.Q}, {"R", KeyCode.R}, {"S", KeyCode.S}, {"T", KeyCode.T},
{"U", KeyCode.U}, {"V", KeyCode.V}, {"W", KeyCode.W}, {"X", KeyCode.X},
{"Y", KeyCode.Y}, {"Z", KeyCode.Z},
{"スペース", KeyCode.Space},
{"エンター", KeyCode.Return},
{"上", KeyCode.UpArrow},
{"下", KeyCode.DownArrow},
{"左", KeyCode.LeftArrow},
{"右", KeyCode.RightArrow},
{"左クリック", KeyCode.Mouse0},
{"右クリック", KeyCode.Mouse1},
{"中クリック", KeyCode.Mouse2},
};
public static void 初期化()
{
foreach (var 項目 in 対応表)
{
string A=項目.Key;
設定(typeof(押す), A, false);
設定(typeof(入力), A, false);
設定(typeof(離す), A, false);
}
設定(typeof(押す), "ホイール上", false);
設定(typeof(押す), "ホイール下", false);
}
public static void 更新()
{
foreach (var 項目 in 対応表)
{
string A = 項目.Key;
KeyCode コードA = 項目.Value;
設定(typeof(押す), A, Input.GetKeyDown(コードA));
設定(typeof(入力), A, Input.GetKey(コードA));
設定(typeof(離す), A, Input.GetKeyUp(コードA));
}
float wheel = Input.GetAxis("Mouse ScrollWheel");
bool 上 = wheel > 0f;
bool 下 = wheel < 0f;
設定(typeof(押す), "ホイール上", 上);
設定(typeof(押す), "ホイール下", 下);
}
static void 設定(System.Type クラス, string 名, bool 値)
{
クラス.GetField(名).SetValue(null, 値);
}
}

