Unity 技能冷卻中 腳本篇


建立時間: 2024年5月21日 02:16
更新時間: 2024年5月21日 02:36

說明

本篇主要分享冷卻器腳本,實現技能冷卻的功能。

設計理念

最初的設計理念是讓任何元素都能實現冷卻功能,因此我首先設計了一個不繼承 MonoBehaviour 的純 class。然而,這種方法有些不便。接著,我考慮使用介面設計,但發現還是不夠便利。然後,我嘗試用 struct,但同樣行不通。經過一番探索,我最終還是決定使用 MonoBehaviour 的方式來設計冷卻功能。

冷卻腳本

Cooldowner.cs

using System;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 冷卻功能
/// </summary>
public class Cooldowner : MonoBehaviour
{
    /// <summary>
    /// 冷卻圖片
    /// </summary>
    [SerializeField]
    private Image cooldownImage;

    /// <summary>
    /// 冷卻時間,注意不是冷卻剩餘時間
    /// </summary>
    [SerializeField]
    private float cooldownTime;

    /// <summary>
    /// 冷卻剩餘時間
    /// </summary>
    private float remainingTime;

    /// <summary>
    /// 冷卻比率,剛冷卻為1,沒有冷卻為0
    /// </summary>
    public float CooldownRate => RemainingTime / cooldownTime;

    /// <summary>
    /// 冷卻時間,注意不是冷卻剩餘時間
    /// </summary>
    public float CooldownTime
    {
        get => cooldownTime;
        set => cooldownTime = value;
    }

    /// <summary>
    /// 冷卻剩餘時間
    /// </summary>
    public float RemainingTime => remainingTime;

    /// <summary>
    /// 是否冷卻中
    /// </summary>
    public bool IsCoolingDown => RemainingTime > 0f;

    private void Awake()
    {
        remainingTime = 0f;
    }

    private void Update()
    {
        UpdateRemainingTime();
        UpdateCooldownImage();
    }

    /// <summary>
    /// 更新冷卻圖片
    /// </summary>
    private void UpdateCooldownImage()
    {
        if (cooldownImage == null)
        {
            return;
        }

        if (!IsCoolingDown)
        {
            return;
        }
        cooldownImage.fillAmount = CooldownRate;
    }

    /// <summary>
    /// 更新冷卻時間
    /// </summary>
    private void UpdateRemainingTime()
    {
        if (!IsCoolingDown)
        {
            return;
        }
        remainingTime = Math.Max(0f, RemainingTime - Time.deltaTime);
    }

    /// <summary>
    /// 開始冷卻,就是將冷卻剩餘時間重置成冷卻時間
    /// </summary>
    public void StartCooldown() => remainingTime = CooldownTime;
}

cooldownImage 是控制冷卻圖片的填充量,關於冷卻的圖片可參考底下的相關文章。

使用方式

建立一個按鈕,新增一個給按鈕的腳本,然後在按鈕添加此腳本的組件,另外再添加冷卻器的組件。

Button add components

按鈕的腳本範例如下:

MyButton.cs

using UnityEngine;

public class MyButton : MonoBehaviour
{
    private Cooldowner cooldowner;

    void Awake()
    {
        cooldowner = GetComponent<Cooldowner>();
        cooldowner.CooldownTime = 5f;
    }

    /// <summary>
    /// 按鈕點擊
    /// </summary>
    public void Click()
    {
        if (cooldowner.IsCoolingDown)
        {
            return;
        }
        // do something

        cooldowner.StartCooldown();
    }
}
觀看次數: 47
buttoncooldownunity

相關文章:

按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!