UGUI—DirectionButton

作者:追风剑情 发布于:2020-7-24 10:53 分类:Unity3d


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using UnityEngine.UI;
/// <summary>
/// 方向按钮
/// 控制面板显示/隐藏
/// </summary>
public class DirectionButton : MonoBehaviour, IPointerClickHandler
{
    [SerializeField]
    private RectTransform m_RectTransform;
    [SerializeField]
    private DirectionLayout directionLayout;
    [SerializeField]
    private UITweenPosition m_TweenPosition;
    [SerializeField]
    private Direction m_Direction;

    [Serializable]
    // 定义按钮OnClick事件类
    public class OnClickEvent : UnityEvent { }

    // 防止序列化变量重命名后丢失引用
    [FormerlySerializedAs("onClick")]
    [SerializeField]
    private OnClickEvent m_OnClick = new OnClickEvent();

    //布局方向
    public enum DirectionLayout
    {
        vertical,
        horizontal
    }

    public enum Direction
    {
        OUT, //指向外
        IN   //指向内
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (m_TweenPosition.active)
            return;

        m_OnClick.Invoke();
        if (m_Direction == Direction.OUT)
            DirectOut();
        else
            DirectIn();
        
    }

    private void DirectOut()
    {
        Debug.Log("DirectOut()");
        m_TweenPosition.Play(); //显示面板
        m_Direction = Direction.IN;
        if (directionLayout == DirectionLayout.horizontal)
            m_RectTransform.localScale = new Vector3(-1, 1, 1);
        else
            m_RectTransform.localScale = new Vector3(1, -1, 1);
    }

    private void DirectIn()
    {
        Debug.Log("DirectIn()");
        m_TweenPosition.InversePlay(); //隐藏面板
        m_Direction = Direction.OUT;
        m_RectTransform.localScale = Vector3.one;
    }
}


测试效果

3335.gif

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号