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

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

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

/// <summary>
/// 自定義按鍵
/// </summary>
public class CustomKey : MonoBehaviour
{
    //聲明Button對(duì)象以進(jìn)行拖拽
    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) //如果已經(jīng)開始記錄新按鍵
            {
                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) //所有已經(jīng)按下的按鍵抬起,停止記錄按鍵
                {
                    CustomButton.SetNewKey(keyCountLimit);
                }
            }
        }
    }
}

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

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

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

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

    public CustomButton(string functionName, Button button, KeyCode[] keycode, int limit)
    {
        FunctionName = functionName;
        BindButton = button;
        if (keycode.Length <= limit) //如果鍵位數(shù)量超過(guò)限制,只保存前幾個(gè)鍵位
        {
            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); //如果有設(shè)定過(guò)新按鈕,則在 PlayerPrefs中讀取按鍵數(shù)量,否則設(shè)為默認(rèn)鍵位的數(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上顯示當(dāng)前綁定的鍵位
        
        BindButton.onClick.RemoveAllListeners(); //Button對(duì)象移除所有監(jiān)聽(tīng)方法      
        BindButton.onClick.AddListener(BtnClick); //Button對(duì)象綁定監(jiān)聽(tīng)方法BtnClick

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

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

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

    /// <summary>
    /// 鍵位沖突檢測(cè)
    /// </summary>
    static void KeyConflictDetection()
    {
        bool repeated = false;
        foreach (CustomButton button in buttonList)
        {
            if (button != currentButton && button.keyList.Count == tempKeyList.Count) //如果兩個(gè)CustomButton對(duì)象鍵位長(zhǎng)度一致
            {
                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顯示的內(nèi)容設(shè)為""  
                }                                  
            }
        }
    }

    /// <summary>
    /// 恢復(fù)默認(rèn)鍵
    /// </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; //等待鍵盤輸入關(guān)閉      
    }

    /// <summary>
    /// 將按鍵內(nèi)容拼接
    /// </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對(duì)象上,canvas隱藏后可以檢測(cè)按鍵設(shè)置是否有效

//UISwitch.cs
using UnityEngine;

public class UISwitch : MonoBehaviour {

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

    void OnDisable()
    {
        CustomButton.isPlaying = true;
        if (CustomButton.isWaitingForKey) //如果正在設(shè)置新按鍵時(shí)關(guān)閉UI,則恢復(fù)原先的按鍵
        {
            CustomButton.currentButton.buttonText.text = CustomButton.MergeText(CustomButton.currentButton.keyList);
            CustomButton.isWaitingForKey = false;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容