Unity3D之UGUI——製作紙牌類遊戲加入房間的輸入面板
阿新 • • 發佈:2018-11-27
Unity3D之UGUI——製作紙牌類遊戲加入房間的輸入面板
在玩紙牌類遊戲,我們經常建立房間,然後邀請好友加入房間進行遊戲。點選加入房間後,彈出加入房間的面板,輸入房號即可加入。
現在我們就利用unity製作一個加入房間的輸入面板,GO GO!
首先我們利用UGUI元件搭建輸入介面,大家可以自行設計樣式,圖片素材可自找,當然如有需要,我會附上我的工程檔案下載地址。搭建介面如下圖:
Button_0至Button_9 表示0至9數字按鍵,Button_reset 為重置,Button_del為刪除,Button_exit為右上方的退出按鈕,
num_group下的6個text為輸入後顯示的房間號。
介面就是這樣,具體的佈置就不詳講了。
程式碼部分:
建立C#指令碼:JoinRoomSettingScript.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class JoinRoomSettingScript : MonoBehaviour { private List<String> inputChars;//輸入的字元 public List<Text> inputTexts;//顯示的text元件 public List<GameObject> btnList;//所有數字按鍵 public Button button_reset, button_del;//撤銷,刪除按鈕 void Start () { inputChars = new List<string>();//例項輸入字元集合 //通過訪問集合,迴圈繫結按鈕的監聽事件 for(int i = 0; i < btnList.Count; i++) { GameObject obj = btnList[i]; btnList[i].GetComponent<Button>().onClick.AddListener(delegate () { this.OnClickHandle(obj);}); } } /// <summary> /// 每幀執行都呼叫onEnterOk()函式 /// </summary> void Update () { onEnterOk(); } /// <summary> /// 數字按鈕點選事件 /// </summary> /// <param name="gobj"></param> public void OnClickHandle(GameObject gobj) { clickNumber(gobj.GetComponentInChildren<Text>().text); } private void clickNumber(string number) { if (inputChars.Count >= 6) { return;//輸入達到6位數,跳出該函式 } inputChars.Add(number); int index = inputChars.Count; inputTexts[index - 1].text = number.ToString();//顯示數字到顯示處 } /// <summary> /// 刪除按鈕的點選事件 /// </summary> public void deleteNumber() { if (inputChars != null && inputChars.Count > 0) { inputChars.RemoveAt(inputChars.Count - 1); inputTexts[inputChars.Count].text = ""; } } /// <summary> /// 重置按鈕的點選事件 /// </summary> public void resetNumber() { if(inputChars !=null && inputChars.Count > 0) { inputChars.Clear(); for(int i=0;i< inputTexts.Count; i++) { inputTexts[i].text = ""; } } } /// <summary> /// 輸入6個字元就提交 /// </summary> private void onEnterOk() { if (inputChars.Count == 6) { String roomNumber = inputChars[0] + inputChars[1] + inputChars[2] + inputChars[3] + inputChars[4] + inputChars[5]; Debug.Log(roomNumber); } } /// <summary> /// 關閉面板 /// </summary> public void closeDialog() { Destroy(this); Destroy(gameObject); } }
將該程式碼掛載載Panel_join _room _bg上,然後並拖動元件到指令碼中宣告的集合中,Input Texts中size輸入6,Btn List 中 size 輸
入 10
然後繫結 Button_reset,Button_del,Button_exit的點選事件
拖動後點擊Founction,選擇 JoinRoomSettingScript----->ResetNummber()
,
我只演示其中一個按鈕繫結,其餘兩個方法相同,相信一定難不倒聰明的你。
繫結完成後,就可以運行了,點選數字按鈕就可以顯示了,
如有不同想法,請互相交流!共同學習! GO GO!繼續成長之路。
如需工程檔案請留言哦,我會盡快發上!當然也可以用NGUI來做,原理一樣。