【Unity實現(xiàn)單機功能】自定義按鍵輸入

實現(xiàn)自定義多個數(shù)的按鍵輸入
將CustomKey.cs掛在空物體上,并將Button對象拖入預留位置

//CustomKey.cs 
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

/// <summary>
/// 自定義按鍵
/// </summary>
public class CustomKey : MonoBehaviour
{
    //聲明Button對象以進行拖拽
    public Button resetBtn;
    public Button jumpBtn;
    public Button getDownBtn;
    public Button leftHeadBtn;
    public Button rightHeadBtn;
    public Button musicSwitchBtn;

    //鍵位數(shù)量限制
    public int keyCountLimit = 2;

    public CustomButton jump;
    public CustomButton getDown;
    public CustomButton leftHead;
    public CustomButton rightHead;
    public CustomButton musicSwitch;

    void Awake()
    {
        resetBtn.onClick.AddListener(CustomButton.ResetBindKeys);
        resetBtn.transform.FindChild("Text").GetComponent<Text>().text = "Reset";                
        jump = new CustomButton("Jump", jumpBtn, new KeyCode[]{ KeyCode.Space}, keyCountLimit);
        getDown = new CustomButton("GetDown", getDownBtn, new KeyCode[] { KeyCode.LeftControl}, keyCountLimit);
        leftHead = new CustomButton("LeftHead", leftHeadBtn, new KeyCode[] { KeyCode.Q}, keyCountLimit);
        rightHead = new CustomButton("RightHead", rightHeadBtn, new KeyCode[] { KeyCode.E}, keyCountLimit);
        musicSwitch = new CustomButton("musicSwitch", musicSwitchBtn, new KeyCode[] { KeyCode.LeftControl, KeyCode.M}, keyCountLimit);     
    }

    void Update()
    {
        if (CustomButton.isPlaying)
        {
            jump.Function();
            getDown.Function();
            leftHead.Function();
            rightHead.Function();
            musicSwitch.Function();
        }
    }

    void OnGUI()
    {
        if (CustomButton.isWaitingForKey)
        {
            Event e = Event.current;
            if (e.isKey && e.keyCode != KeyCode.None)
            {                
                if (!CustomButton.tempKeyList.Contains(e.keyCode)) //如果list中不包含該按鍵毁涉,則記錄按鍵
                {
                    CustomButton.tempKeyList.Add(e.keyCode);
                    CustomButton.tempPressList.Add(false);                    
                    CustomButton.currentButton.buttonText.text = CustomButton.MergeText(CustomButton.tempKeyList, keyCountLimit);
                }      
            }
            if (CustomButton.tempKeyList.Count > 0) //如果已經開始記錄新按鍵
            {
                bool result = true;
                for (int i = 0; i < CustomButton.tempKeyList.Count ; i++)
                {
                    if(Input.GetKey(CustomButton.tempKeyList[i])) 
                        CustomButton.tempPressList[i] = false;                                   
                    else
                        CustomButton.tempPressList[i] = true;
                }
                for (int i = 0; i < CustomButton.tempKeyList.Count; i++)
                {
                    result = result & CustomButton.tempPressList[i];
                }
                if (result) //所有已經按下的按鍵抬起淀弹,停止記錄按鍵
                {
                    CustomButton.SetNewKey(keyCountLimit);
                }
            }
        }
    }
}

/// <summary>
/// 將屏幕上的Button與實際鍵盤按鈕、名稱綁定
/// </summary>
public class CustomButton
{
    string FunctionName { set; get; } //功能名稱
    public Button BindButton { private set; get; } //屏幕上的Button對象
    KeyCode[] DefaultKey; //默認綁定的鍵位

    int keyCount; //鍵位數(shù)量
    public List<KeyCode> keyList; //當前綁定的鍵位    
    List<bool> pressList; //記錄每個鍵位的狀態(tài)
    public Text buttonText; //Button上顯示的內容

    public static bool isWaitingForKey = false; //等待鍵盤輸入狀態(tài)
    public static bool isPlaying = false; //游戲狀態(tài)

    public static CustomButton currentButton; //當前指向的CustomButton
    public static List<KeyCode> tempKeyList = new List<KeyCode>(); //臨時存儲的鍵位
    public static List<bool> tempPressList = new List<bool>(); //臨時鍵位的狀態(tài)
    static List<CustomButton> buttonList = new List<CustomButton>(); //包含所有CustomButton對象的list

    public CustomButton(string functionName, Button button, KeyCode[] keycode, int limit)
    {
        FunctionName = functionName;
        BindButton = button;
        if (keycode.Length <= limit) //如果鍵位數(shù)量超過限制,只保存前幾個鍵位
        {
            DefaultKey = keycode;
        }
        else
        {
            DefaultKey = new KeyCode[limit];
            for (int i = 0; i < limit; i++)
            {
                DefaultKey[i] = keycode[i];
            }
        }
        
        keyCount = PlayerPrefs.GetInt(FunctionName + "keyCount", DefaultKey.Length); //如果有設定過新按鈕肢础,則在 PlayerPrefs中讀取按鍵數(shù)量蕴坪,否則設為默認鍵位的數(shù)量
        keyList = new List<KeyCode>();
        pressList = new List<bool>();

        for (int i = 0; i < keyCount; i++)
        {
            keyList.Add((KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString(FunctionName + i.ToString(), (i < DefaultKey.Length ? DefaultKey[i].ToString() : null)))); //讀取按鍵
            pressList.Add(false);
        }            
            
        buttonText = BindButton.transform.Find("Text").GetComponent<Text>();
        buttonText.text = MergeText(keyList); //在Button上顯示當前綁定的鍵位
        
        BindButton.onClick.RemoveAllListeners(); //Button對象移除所有監(jiān)聽方法      
        BindButton.onClick.AddListener(BtnClick); //Button對象綁定監(jiān)聽方法BtnClick

        buttonList.Add(this); //將自己加入list
    }

    public void BtnClick()
    {
        if (currentButton != this) //如果當前指向的按鈕不是自己
        {
            if (currentButton != null) //當前指向的按鈕不為空肴掷,恢復在之前Button上顯示綁定的鍵位            
                currentButton.buttonText.text = MergeText(currentButton.keyList);
            currentButton = this; //將當前指向的按鈕指向自己
        }
        buttonText.text = ""; //將Button上顯示的內容設置為""
        tempKeyList.Clear();
        tempPressList.Clear();
        isWaitingForKey = true; //等待鍵盤輸入開啟
    }

    /// <summary>
    /// 設置新按鍵
    /// </summary>
    /// <param name="limit"></param>
    public static void SetNewKey(int limit)
    {
        if (tempKeyList.Count > limit) //如果鍵位數(shù)量超過限制敬锐,只保存前幾個和最后一個鍵位
        {
            tempKeyList[limit - 1] = tempKeyList[tempKeyList.Count - 1];
            tempKeyList.RemoveRange(limit, tempKeyList.Count - limit);
        }
        KeyConflictDetection();
        currentButton.keyList.Clear();
        currentButton.pressList.Clear();
        for (int i = 0; i < tempKeyList.Count; i++)
        {
            currentButton.keyList.Add(tempKeyList[i]); //將當前指向的按鈕綁定的鍵位設為傳入的鍵位
            currentButton.pressList.Add(false);
            PlayerPrefs.SetString(currentButton.FunctionName + i.ToString(), currentButton.keyList[i].ToString()); //將設置的鍵位存入PlayerPrefs,這樣可以在重新運行程序后進行讀取
        }        
        currentButton.keyCount = currentButton.keyList.Count;
        PlayerPrefs.SetInt(currentButton.FunctionName + "keyCount", currentButton.keyCount);
        currentButton.buttonText.text = MergeText(currentButton.keyList); //在當前指向的按鈕的Button上顯示當前綁定的鍵位 
        isWaitingForKey = false; //等待鍵盤輸入關閉
    }

    /// <summary>
    /// 鍵位沖突檢測
    /// </summary>
    static void KeyConflictDetection()
    {
        bool repeated = false;
        foreach (CustomButton button in buttonList)
        {
            if (button != currentButton && button.keyList.Count == tempKeyList.Count) //如果兩個CustomButton對象鍵位長度一致
            {
                for (int i = 0; i < tempKeyList.Count; i++)
                {
                    if (!button.keyList.Contains(tempKeyList[i]))
                    {
                        repeated = false;
                        break;
                    }
                    repeated = true;                     
                }
                if (repeated)
                {
                    button.keyList.Clear();
                    button.pressList.Clear();
                    button.buttonText.text = ""; //將Button顯示的內容設為""  
                }                                  
            }
        }
    }

    /// <summary>
    /// 恢復默認鍵
    /// </summary>
    public static void ResetBindKeys()
    {        
        PlayerPrefs.DeleteAll();
        foreach (CustomButton button in buttonList)
        {
            button.keyList.Clear();
            button.pressList.Clear();
            button.keyCount = button.DefaultKey.Length;
            PlayerPrefs.SetInt(button.FunctionName + "keyCount", button.keyCount);
            for (int i = 0; i < button.keyCount; i++)
            {
                if (!button.keyList.Contains(button.DefaultKey[i])) //如果list中不包含該按鍵呆瞻,則加入list
                {
                    button.keyList.Add(button.DefaultKey[i]);
                    button.pressList.Add(false);
                    PlayerPrefs.SetString(button.FunctionName + i.ToString(), button.DefaultKey[i].ToString());                    
                }
            }
            button.buttonText.text = MergeText(button.keyList);
        }
        isWaitingForKey = false; //等待鍵盤輸入關閉      
    }

    /// <summary>
    /// 將按鍵內容拼接
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public static string MergeText(List<KeyCode> e)
    {
        string text = null;
        for (int i = 0; i < e.Count; i++)
        {
            text += e[i].ToString();
            if (e.Count - i > 1)
                text += "+";
        }
        return text;
    }

    public static string MergeText(List<KeyCode> e, int limit)
    {
        if (e.Count <= limit)
            return MergeText(e);
        else
        {
            List<KeyCode> temp = new List<KeyCode>();
            for (int i = 0; i < limit - 1; i++)
            {
                temp.Add(e[i]);
            }
            temp.Add(e[e.Count-1]);
            return MergeText(temp);
        }
    }


    bool functionState = false;
    public void Function()
    {
        bool result = true;

        for (int i = 0; i < keyList.Count; i++)
        {
            if (Input.GetKey(keyList[i]))
            {
                pressList[i] = true;
            }
            else
            {
                pressList[i] = false;
                functionState = false;
            }
        }

        for (int i = 0; i < keyList.Count; i++)
        {
            result = result & pressList[i];
        }

        if (result && !functionState)
        {
            Debug.Log(FunctionName);
            functionState = true;
        }            
    }
}

UISwitch.cs掛在canvas對象上台夺,canvas隱藏后可以檢測按鍵設置是否有效

//UISwitch.cs
using UnityEngine;

public class UISwitch : MonoBehaviour {

    void OnEnable()
    {
        CustomButton.isPlaying = false;
    }

    void OnDisable()
    {
        CustomButton.isPlaying = true;
        if (CustomButton.isWaitingForKey) //如果正在設置新按鍵時關閉UI,則恢復原先的按鍵
        {
            CustomButton.currentButton.buttonText.text = CustomButton.MergeText(CustomButton.currentButton.keyList);
            CustomButton.isWaitingForKey = false;
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末痴脾,一起剝皮案震驚了整個濱河市颤介,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌赞赖,老刑警劉巖滚朵,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異前域,居然都是意外死亡辕近,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門匿垄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來移宅,“玉大人,你說我怎么就攤上這事椿疗⊥毯迹” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵变丧,是天一觀的道長芽狗。 經常有香客問我,道長痒蓬,這世上最難降的妖魔是什么童擎? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮攻晒,結果婚禮上顾复,老公的妹妹穿的比我還像新娘。我一直安慰自己鲁捏,他們只是感情好芯砸,可當我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著给梅,像睡著了一般假丧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上动羽,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天包帚,我揣著相機與錄音,去河邊找鬼运吓。 笑死渴邦,一個胖子當著我的面吹牛疯趟,可吹牛的內容都是我干的。 我是一名探鬼主播谋梭,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼信峻,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了瓮床?” 一聲冷哼從身側響起盹舞,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎纤垂,沒想到半個月后矾策,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體磷账,經...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡峭沦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了逃糟。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吼鱼。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖绰咽,靈堂內的尸體忽然破棺而出菇肃,到底是詐尸還是另有隱情,我是刑警寧澤取募,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布琐谤,位于F島的核電站,受9級特大地震影響玩敏,放射性物質發(fā)生泄漏斗忌。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一旺聚、第九天 我趴在偏房一處隱蔽的房頂上張望织阳。 院中可真熱鬧,春花似錦砰粹、人聲如沸唧躲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽弄痹。三九已至,卻和暖如春嵌器,著一層夾襖步出監(jiān)牢的瞬間界酒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工嘴秸, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留毁欣,地道東北人庇谆。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像凭疮,于是被迫代替她去往敵國和親饭耳。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內容