UGUI—UITweenScale

作者:追风剑情 发布于:2020-3-31 14:25 分类: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>
/// UI缩放缓动
/// </summary>
public class UITweenScale : MonoBehaviour
{
    public enum ComponentType
    {
        Transform,
        Text
    }
    public ComponentType componentType;
    public bool active = false;
    [Tooltip("延迟执行")]
    public float delayTime = 0;
    public RectTransform rectTransform;
    public Vector3 from;
    public Vector3 to;
    public float fontSizeFrom;
    public float fontSizeTo;
    public float speed;
    public bool inverse = false;
    private Text text;

    [Serializable]
    // 定义缓动完成后要触发的事件
    public class TweenCompletedEvent : UnityEvent { }

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

    private float t = 0;
    private float escapeTime = 0;

    public void Reset()
    {
        if (componentType == ComponentType.Transform)
            rectTransform.localScale = from;
        else
            text.fontSize = (int)fontSizeFrom;
    }

    void Awake()
    {
        if (rectTransform == null)
            rectTransform = this.GetComponent<RectTransform>();
        if (componentType == ComponentType.Text)
            text = this.GetComponent<Text>();
    }

    void Update()
    {
        if (!active)
            return;

        escapeTime += Time.deltaTime;
        if (escapeTime < delayTime)
            return;

        t += speed * Time.deltaTime;
        if (componentType == ComponentType.Transform)
        {
            if (inverse)
                rectTransform.localScale = Vector3.Lerp(to, from, t);
            else
                rectTransform.localScale = Vector3.Lerp(from, to, t);

        }
        else
        {
            if (inverse)
                text.fontSize = (int)Mathf.Lerp(fontSizeTo, fontSizeFrom, t);
            else
                text.fontSize = (int)Mathf.Lerp(fontSizeFrom, fontSizeTo, t);
        }

        if (t >= 1)
        {
            t = 0;
            active = false;
            m_OnCompleted.Invoke();
        }
    }

    public void Play()
    {
        t = 0;
        escapeTime = 0;
        active = true;
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号