UGUI—UISwitchButton

作者:追风剑情 发布于:2020-9-9 14:14 分类:Unity3d

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

/// <summary>
/// 开关按钮
/// </summary>
public class UISwitchButton : MonoBehaviour
{
    [SerializeField]
    private Text m_Text;
    [SerializeField]
    private Image m_Image;

    public Sprite openSprite;
    public Sprite closeSprite;

    public string openText;
    public string closeText;

    [SerializeField]
    private ButtonState m_State;

    [Serializable]
    public class OnOpenEvent : UnityEvent { }
    [Serializable]
    public class OnCloseEvent : UnityEvent { }

    [FormerlySerializedAs("onOpen")]
    [SerializeField]
    private OnOpenEvent m_OnOpen = new OnOpenEvent();

    [FormerlySerializedAs("onClose")]
    [SerializeField]
    private OnOpenEvent m_OnClose = new OnOpenEvent();

    public enum ButtonState
    {
        Open,
        Close
    }

    public void Reset()
    {
        m_State = ButtonState.Open;
        UpdateDisplay();
    }

    public void UpdateDisplay()
    {
        if (m_State == ButtonState.Open)
        {
            if (m_Text != null)
                m_Text.text = openText;
            if (m_Image != null)
                m_Image.sprite = openSprite;
        }
        else
        {
            if (m_Text != null)
                m_Text.text = closeText;
            if (m_Image != null)
                m_Image.sprite = closeSprite;
        }
    }

    public void OnClick()
    {
        m_State = (m_State == ButtonState.Open) ? ButtonState.Close : ButtonState.Open;
        UpdateDisplay();
        if (m_State == ButtonState.Open)
            m_OnOpen.Invoke();
        else
            m_OnClose.Invoke();
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号