Unity3D 모방 버튼 패 널 이벤트 귀속 기능

본 논문 의 사례 는 유 니 티 3D 모방 Button 패 널 이벤트 바 인 딩 기능 의 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
최근 에 줄 거 리 를 안내 하 는 프로젝트 를 하고 있다.그 중의 한 가지 수요 특징 은 모든 단계 에 비슷 한 정 보 를 표시 해 야 한 다 는 것 이다.다른 것 은 매번 게이머 들 이 놀 도록 유도 해 야 하 는 것 이 다르다 는 것 이다.예 를 들 어 첫 번 째 단 계 는 물체 1 을 표시 해 야 하고 두 번 째 단 계 는 물체 2 를 표시 해 야 한다.차이 점 은 같은 스 크 립 트 에서 서로 다른 함 수 를 호출 하 는 것 이다.우 리 는 매번 다른 설정 을 위해 서로 다른 스 크 립 트 를 쓸 수 없습니다.만약 천 여 걸음 이 라면 천 여 개의 스 크 립 트 를 써 야 합 니까?갑자기 유 니 티 를 원 하 는 UGUI 에서 button 이벤트 의 연결 은 좋 은 해결 방안 입 니 다.그래서 나 는 인터넷 에서 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);
  }
 }
}
코드 는 사실 매우 간단 합 니 다.주로 자신의 새로운 유 니 티 이벤트 입 니 다.그리고 우 리 는 외부 에서 호출 합 니 다.이 Unity Event 는 판 넬 에 직렬 화 되 어 표 시 됩 니 다.우 리 는 두 가지 방식 으로 사건 을 연결 할 수 있다.첫 번 째 는 패 널 에 연결 하 는 것 이 고,두 번 째 는 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()를 실행 합 니 다.유 니 티 자체 메시지 이 벤트 를 사용 하면 개발 이 훨씬 수월 해 집 니 다.유 니 티 이 벤트 를 사용 하지 않 으 면 StepControl 에서 우리 의 의뢰 를 설명 할 수 있 지만 작은 작업 을 호출 할 때 코드 를 더 써 야 합 니 다.예 를 들 어 우 리 는 어떤 물 체 를 숨 기 려 면 스 크 립 트 를 따로 써 서 물체 의 숨 김 을 설정 하고 함 수 를 이 StepControl 의 의뢰 에 연결 해 야 합 니 다.유 니 티 이벤트 에 서 는 패 널 조작 을 통 해 직접 이 루어 질 수 있 습 니 다.

이상 은 제 블 로그 내용 입 니 다.오류 가 있 습 니 다.지적 을 환영 합 니 다!
올 해 는 코드 재 구축+shader 효과 의 초급 작성 을 배 워 야 합 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기