UI页面切换按钮随页面切换缩放

选中按钮放大其余按钮缩小的
效果:

UI页面切换按钮随页面切换缩放_第1张图片在这里插入图片描述
UI页面切换按钮随页面切换缩放_第2张图片

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BottomBarBtn : MonoBehaviour
{
    public RectTransform rect;
    public GameObject[] active;
    public Transform icon;
    float maxWidth = 360f;
    float minWidth = 180f;
    float maxScale = 1.5f;

    Coroutine closing;
    Coroutine expanding;
    bool isClose;
    public bool isPlaying;
    float width
    {
        get
        {
            return rect.sizeDelta.x;
        }
        set
        {
            Vector2 size = rect.sizeDelta;
            size.x = value;
            rect.sizeDelta = size;
        }
    }
    

    public void SetOpen(bool open)
    {
        isPlaying = false;
        float to = open ? maxWidth : minWidth;
        Vector3 toScale = !open ? Vector3.one : Vector3.one * maxScale;
        width = to;
        isClose = !open;
        icon.transform.localScale = toScale;
        SetActiveImg(open);
    }

    public void OpenBtn()
    {
        if (closing != null)
        {
            isPlaying = false;
            StopCoroutine(closing);
            closing = null;
        }
        if (expanding != null || !isClose) return;
        expanding = StartCoroutine(ExpandBtn(true));
        SetActiveImg(true);
    }


    public void CloseBtn()
    {

        if (expanding != null)
        {
            isPlaying = false;
            StopCoroutine(expanding);
            expanding = null;
        }
        if (closing != null || isClose) return;
        expanding = StartCoroutine(ExpandBtn(false));
        SetActiveImg(false);
    }

    void SetActiveImg(bool boolean)
    {
        foreach (GameObject obj in active)
        {
            obj.gameObject.SetActive(boolean);
        }
    }

    IEnumerator ExpandBtn(bool toBig)
    {
        float timer = 0;
        float time = 0.2f;
        isPlaying = true;
        float to = !toBig ? minWidth : maxWidth;
        Vector3 toScale = Vector3.one * (toBig ? maxScale : 1);
        float wFrom = width;
        Vector3 fromScale = icon.transform.localScale;
        while (timer < time)
        {
            width = rect.sizeDelta.x;
            timer += Time.deltaTime;
            float t = timer / time;
            float wCur = Mathf.Lerp(width, to, t);
            Vector3 curScale = Vector3.Lerp(fromScale, toScale, t);

            icon.transform.localScale = curScale;
            width = wCur;
            yield return null;
        }
        isPlaying = false;
        closing = null;
        expanding = null;
        width = to;
        isClose = !toBig;
        icon.transform.localScale = toScale;
    }
}

你可能感兴趣的:(unity,UGUI)