溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Unity3D中怎么實(shí)現(xiàn)Button面板事件綁定功能

發(fā)布時(shí)間:2021-06-17 14:33:50 來源:億速云 閱讀:482 作者:Leah 欄目:編程語言

這篇文章給大家介紹Unity3D中怎么實(shí)現(xiàn)Button面板事件綁定功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

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);
  }
 }
}

代碼其實(shí)挺簡單的,主要是自己new 一個(gè)新的unityEvent,然后我們在外界調(diào)用。這個(gè)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();
  }
 }
}

我們將腳本掛到空物體上,效果如下:

Unity3D中怎么實(shí)現(xiàn)Button面板事件綁定功能

使用方法如下例子:

我們自己寫一個(gè)步驟設(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聲明一個(gè)我們自己的委托,但是去調(diào)用小的操作的時(shí)候會需要多寫一點(diǎn)代碼。比如 我們想讓某個(gè)物體隱藏,需要單獨(dú)寫一個(gè)腳本設(shè)置物體隱藏并且將函數(shù)綁定到此StepControl的委托上。而在UnityEvent里可以直接通過面板操作實(shí)現(xiàn)。

Unity3D中怎么實(shí)現(xiàn)Button面板事件綁定功能

關(guān)于Unity3D中怎么實(shí)現(xiàn)Button面板事件綁定功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI