Unity3D仿寫B(tài)utton面板事件綁定功能
本文實例為大家分享了Unity3D仿寫B(tài)utton面板事件綁定功能的具體代碼,供大家參考,具體內(nèi)容如下
最近在做一個情節(jié)引導(dǎo)得項目。其中一個需求特點是:每一步都要顯示類似的信息,不同的是,每一次要去引導(dǎo)玩家玩的東西不同。比如:第一步需要顯示物體1,第二步需要顯示物體2,區(qū)別就是在相同的腳本調(diào)用不同的函數(shù)。我們不可能為了每一次不同的設(shè)置寫不同的腳本,如果一千多步,難道要寫一千多個腳本?突然想要unity 的UGUI中button事件的綁定是一個好的解決方案。于是我上網(wǎng)搜索了button的源代碼。如下:
using System; using System.Collections; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.Serialization; namespace UnityEngine.UI { // Button that's meant to work with mouse or touch-based devices. [AddComponentMenu("UI/Button", 30)] public class Button : Selectable, IPointerClickHandler, ISubmitHandler { [Serializable] /// <summary> /// Function definition for a button click event. /// </summary> public class ButtonClickedEvent : UnityEvent {} // Event delegates triggered on click. [FormerlySerializedAs("onClick")] [SerializeField] private ButtonClickedEvent m_OnClick = new ButtonClickedEvent(); protected Button() {} /// <summary> /// UnityEvent that is triggered when the button is pressed. /// Note: Triggered on MouseUp after MouseDown on the same object. /// </summary> ///<example> ///<code> /// using UnityEngine; /// using UnityEngine.UI; /// using System.Collections; /// /// public class ClickExample : MonoBehaviour /// { /// public Button yourButton; /// /// void Start() /// { /// Button btn = yourButton.GetComponent<Button>(); /// btn.onClick.AddListener(TaskOnClick); /// } /// /// void TaskOnClick() /// { /// Debug.Log("You have clicked the button!"); /// } /// } ///</code> ///</example> public ButtonClickedEvent onClick { get { return m_OnClick; } set { m_OnClick = value; } } private void Press() { if (!IsActive() || !IsInteractable()) return; UISystemProfilerApi.AddMarker("Button.onClick", this); m_OnClick.Invoke(); } /// <summary> /// Call all registered IPointerClickHandlers. /// Register button presses using the IPointerClickHandler. You can also use it to tell what type of click happened (left, right etc.). /// Make sure your Scene has an EventSystem. /// </summary> /// <param name="eventData">Pointer Data associated with the event. Typically by the event system.</param> /// <example> /// <code> /// //Attatch this script to a Button GameObject /// using UnityEngine; /// using UnityEngine.EventSystems; /// /// public class Example : MonoBehaviour, IPointerClickHandler /// { /// //Detect if a click occurs /// public void OnPointerClick(PointerEventData pointerEventData) /// { /// //Use this to tell when the user right-clicks on the Button /// if (pointerEventData.button == PointerEventData.InputButton.Right) /// { /// //Output to console the clicked GameObject's name and the following message. You can replace this with your own actions for when clicking the GameObject. /// Debug.Log(name + " Game Object Right Clicked!"); /// } /// /// //Use this to tell when the user left-clicks on the Button /// if (pointerEventData.button == PointerEventData.InputButton.Left) /// { /// Debug.Log(name + " Game Object Left Clicked!"); /// } /// } /// } /// </code> /// </example> public virtual void OnPointerClick(PointerEventData eventData) { if (eventData.button != PointerEventData.InputButton.Left) return; Press(); } /// <summary> /// Call all registered ISubmitHandler. /// </summary> /// <param name="eventData">Associated data with the event. Typically by the event system.</param> /// <remarks> /// This detects when a Button has been selected via a "submit" key you specify (default is the return key). /// /// To change the submit key, either: /// /// 1. Go to Edit->Project Settings->Input. /// /// 2. Next, expand the Axes section and go to the Submit section if it exists. /// /// 3. If Submit doesn't exist, add 1 number to the Size field. This creates a new section at the bottom. Expand the new section and change the Name field to “Submit”. /// /// 4. Change the Positive Button field to the key you want (e.g. space). /// /// /// Or: /// /// 1. Go to your EventSystem in your Project /// /// 2. Go to the Inspector window and change the Submit Button field to one of the sections in the Input Manager (e.g. "Submit"), or create your own by naming it what you like, then following the next few steps. /// /// 3. Go to Edit->Project Settings->Input to get to the Input Manager. /// /// 4. Expand the Axes section in the Inspector window. Add 1 to the number in the Size field. This creates a new section at the bottom. /// /// 5. Expand the new section and name it the same as the name you inserted in the Submit Button field in the EventSystem. Set the Positive Button field to the key you want (e.g. space) /// </remarks> public virtual void OnSubmit(BaseEventData eventData) { Press(); // if we get set disabled during the press // don't run the coroutine. if (!IsActive() || !IsInteractable()) return; DoStateTransition(SelectionState.Pressed, false); StartCoroutine(OnFinishSubmit()); } private IEnumerator OnFinishSubmit() { var fadeTime = colors.fadeDuration; var elapsedTime = 0f; while (elapsedTime < fadeTime) { elapsedTime += Time.unscaledDeltaTime; yield return null; } DoStateTransition(currentSelectionState, false); } } }
代碼其實挺簡單的,主要是自己new 一個新的unityEvent,然后我們在外界調(diào)用。這個UnityEvent通過序列化顯示在面板上。我們可以通過兩種方式綁定事件。第一種就是在面板綁定,第二種就是AddListener添加事件。于是我們可以照貓畫虎擇取我們自己需要的部份寫我們自己需要的事件綁定。代碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.Serialization; using System; namespace MyEvent { public class MyCompotent : MonoBehaviour { [Serializable] public class MyCompontentEvent:UnityEvent{ } [FormerlySerializedAs("MyEvent")] [SerializeField] private MyCompontentEvent myEvent = new MyCompontentEvent(); public MyCompontentEvent MyEvent { get { return myEvent; }set { myEvent = value; } } //執(zhí)行綁定的事件 public void ExcuteEvent() { MyEvent.Invoke(); } } }
我們將腳本掛到空物體上,效果如下:
使用方法如下例子:
我們自己寫一個步驟設(shè)置器,代碼如下:
namespace MyEvent { public class StepControl : MyCompotent { public string Name; public int Index; private void Start() { //設(shè)置名字 //設(shè)置Index //去做每一步應(yīng)該設(shè)置得事情 ExcuteEvent(); } } }
我們在StepControl里設(shè)置相同的操作。不同的操作通過面板綁定讓ExcuteEvent()去執(zhí)行。使用unity自帶的消息事件會讓我們開發(fā)輕松很多。如果不使用UnityEvent,我們也可以在StepControl聲明一個我們自己的委托,但是去調(diào)用小的操作的時候會需要多寫一點代碼。比如 我們想讓某個物體隱藏,需要單獨寫一個腳本設(shè)置物體隱藏并且將函數(shù)綁定到此StepControl的委托上。而在UnityEvent里可以直接通過面板操作實現(xiàn)。
以上為我的博客內(nèi)容。有錯誤歡迎指點!
今年一定要學(xué)會代碼重新建模+shader效果的初級編寫。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持我們。
欄 目:C#教程
下一篇:Unity實現(xiàn)旋轉(zhuǎn)扭曲圖像特效
本文標題:Unity3D仿寫B(tài)utton面板事件綁定功能
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/4892.html
您可能感興趣的文章
- 01-10C#動態(tài)創(chuàng)建button的方法
- 01-10Winform消除button按下出現(xiàn)的虛線簡單實現(xiàn)方法
- 01-10Unity3d獲取系統(tǒng)時間
- 01-10Unity3D獲取當前鍵盤按鍵及Unity3D鼠標、鍵盤的基本操作
- 01-10學(xué)習Winform文本類控件(Label、Button、TextBox)
- 01-10MessageBox的Buttons和三級聯(lián)動效果
- 01-10C#動態(tài)創(chuàng)建button按鈕的方法實例詳解
- 01-10WPF自定義控件和樣式之自定義按鈕(Button)
- 01-10Unity3D實現(xiàn)批量下載圖片功能
- 01-10Unity3d實現(xiàn)Flappy Bird游戲


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已
隨機閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 04-02jquery與jsp,用jquery
- 01-10C#中split用法實例總結(jié)