您好,登錄后才能下訂單哦!
這篇文章給大家介紹Unity3D中怎么實現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,然后我們在外界調用。這個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; } } //執行綁定的事件 public void ExcuteEvent() { MyEvent.Invoke(); } } }
我們將腳本掛到空物體上,效果如下:
使用方法如下例子:
我們自己寫一個步驟設置器,代碼如下:
namespace MyEvent { public class StepControl : MyCompotent { public string Name; public int Index; private void Start() { //設置名字 //設置Index //去做每一步應該設置得事情 ExcuteEvent(); } } }
我們在StepControl里設置相同的操作。不同的操作通過面板綁定讓ExcuteEvent()去執行。使用unity自帶的消息事件會讓我們開發輕松很多。如果不使用UnityEvent,我們也可以在StepControl聲明一個我們自己的委托,但是去調用小的操作的時候會需要多寫一點代碼。比如 我們想讓某個物體隱藏,需要單獨寫一個腳本設置物體隱藏并且將函數綁定到此StepControl的委托上。而在UnityEvent里可以直接通過面板操作實現。
關于Unity3D中怎么實現Button面板事件綁定功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。