unity计时器功能的实现

26 篇文章 1 订阅

最近在游戏开发的过程中需要做一些技能cd, buff持续时间的控制等功能,这些功能都需要一个计时器;

为了便利开发,自己写了一个简单的计时器,这样大部分有关计时的都可以用此计时器了;

计时器主要实现功能:

在规定的时间内倒计时,其中可以暂停,可以继续,可以设置是否受时间速率的影响等;

倒计时过程中可以时刻返回倒计时的状态;

可以获取倒计时剩余时间,倒计时结束的回调。

......


以下代码在unity中测试通过:


计时器代码

using UnityEngine;
using System.Collections;
using System;

public delegate void CompleteEvent();
public delegate void UpdateEvent(float t);

public class Timer : MonoBehaviour
{
    bool isLog = true;

    UpdateEvent updateEvent ;

    CompleteEvent onCompleted ;
	 
    float timeTarget;   // 计时时间/

    float timeStart;    // 开始计时时间/

    float timeNow;     // 现在时间/

    float offsetTime;   // 计时偏差/

    bool isTimer;       // 是否开始计时/

    bool isDestory = true;     // 计时结束后是否销毁/

    bool isEnd;         // 计时是否结束/

    bool isIgnoreTimeScale = true;  // 是否忽略时间速率

    bool isRepeate;

    float Time_
    {
        get { return isIgnoreTimeScale ? Time.realtimeSinceStartup : Time.time; }
    }
    float now;
    // Update is called once per frame
    void Update()
    {
        if (isTimer)
        {
            timeNow = Time_ - offsetTime;
            now = timeNow - timeStart;
            if (updateEvent != null)
                updateEvent(Mathf.Clamp01(now / timeTarget));
            if (now > timeTarget)
            {
                if (onCompleted != null)
                    onCompleted();
                if (!isRepeate)
                    destory();
                else
                    reStartTimer();
            }
        }
    }
    public float GetLeftTime()
    {
        return Mathf.Clamp(timeTarget - now, 0, timeTarget);
    }
    void OnApplicationPause(bool isPause_)
    {
        if (isPause_)
        {
            pauseTimer();
        }
        else
        {
            connitueTimer();
        }
    }

    /// <summary>
    /// 计时结束
    /// </summary>
    public void destory()
    {
        isTimer = false;
        isEnd = true;
        if (isDestory)
            Destroy(gameObject);
    }
    float _pauseTime;
    /// <summary>
    /// 暂停计时
    /// </summary>
    public void pauseTimer()
    {
        if (isEnd)
        {
            if (isLog) Debug.LogWarning("计时已经结束!");
        }
        else
        {
            if(isTimer)
	   {
            	isTimer = false;
            	_pauseTime= Time_;
	   }	
        }
    }
    /// <summary>
    /// 继续计时
    /// </summary>
    public void connitueTimer()
    {
        if (isEnd)
        {
            if (isLog) Debug.LogWarning("计时已经结束!请从新计时!");
        }
        else
        {
            if (!isTimer)
            {
                offsetTime += (Time_ - _pauseTime);
                isTimer = true;
            }
        }
    }
    public void reStartTimer()
    {
        timeStart = Time_;
        offsetTime = 0;
    }

    public void changeTargetTime(float time_)
    {
        timeTarget += time_;
    }
    /// <summary>
    /// 开始计时 : 
    /// </summary>
    public void startTiming(float time_, CompleteEvent onCompleted_, UpdateEvent update = null, bool isIgnoreTimeScale_ = true, bool isRepeate_ = false, bool isDestory_ = true)
    {
        timeTarget = time_;
		if (onCompleted_ != null)
            onCompleted = onCompleted_;
		if (update != null)
            updateEvent = update;
        isDestory = isDestory_;
        isIgnoreTimeScale = isIgnoreTimeScale_;
        isRepeate = isRepeate_;

        timeStart = Time_;
        offsetTime = 0;
        isEnd = false;
        isTimer = true;

    }
    /// <summary>
    /// 创建计时器:名字
    /// </summary>
    public static Timer createTimer(string gobjName = "Timer")
    {
        GameObject g = new GameObject(gobjName);
        Timer timer = g.AddComponent<Timer>();
        return timer;
    }

}



以上是计时器功能的实现;怎么用这个计时器呢?


我们可以在需要计时器的脚本中这样去创建一个计时器:


实现代码:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{

	// Use this for initialization
	void Start ()
	{
		// 创建计时器
		Timer timer = Timer.createTimer ("Timer");
		//开始计时
		timer.startTiming (1, OnComplete, OnProcess);
	}
	
	// Update is called once per frame
	void Update ()
	{
	
	}
	// 计时结束的回调
	void OnComplete ()
	{
		Debug.Log ("complete !");
	}
	// 计时器的进程
	void OnProcess (float p)
	{
		Debug.Log ("on process " + p);
	}
}

测试脚本中只写出了如何创建和简单使用计时器,像一些控制计时器的暂停,继续,获取剩余时间等等一系列的功能可以自己测试一下。


  • 16
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值