UGUI—UIMultipleStateButton

作者:追风剑情 发布于:2024-6-19 12:15 分类: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 UIMultipleStateButton : MonoBehaviour, IPointerClickHandler
{
    //按钮图片
    [SerializeField]
    private Image m_ButtonImage;
    //按钮文本框
    [SerializeField]
    private Text m_ButtonText;
    //按钮状态图片
    [SerializeField]
    private List<Sprite> m_SpriteStateList = new List<Sprite>();
    //按钮状态文本
    [SerializeField]
    private List<string> m_TextStateList = new List<string>();
    //当前状态索引
    private int m_StateIndex = 0;

    [Serializable]
    public class StateChangedEvent : UnityEvent<UIMultipleStateButton> { }

    [FormerlySerializedAs("onChangedState")]
    [SerializeField]
    private StateChangedEvent m_OnChangedState = new StateChangedEvent();

    // 状态个数
    public int StateCount
    {
        get
        {
            int spriteCount = m_SpriteStateList.Count;
            int textCount = m_TextStateList.Count;
            if (spriteCount > textCount) 
                return spriteCount;
            return textCount;
        }
    }

    // 状态索引
    public int StateIndex
    {
        get { return m_StateIndex; }
        set { ChangeState(value); }
    }

    // 切换按钮状态
    public void ChangeState(int index)
    {
        if (m_StateIndex == index) return;
        ChangeStateWithoutNotify(index);
        m_OnChangedState?.Invoke(this);
    }

    // 切换按钮状态,不触发事件
    public void ChangeStateWithoutNotify(int index)
    {
        if (m_StateIndex == index) return;

        if (index < m_SpriteStateList.Count)
            m_ButtonImage.sprite = m_SpriteStateList[index];

        if (index < m_TextStateList.Count)
            m_ButtonText.text = m_TextStateList[index];

        m_StateIndex = index;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        int index = (m_StateIndex + 1) % StateCount;
        ChangeState(index);
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号