朱峰社區(qū)首頁 朱峰社區(qū)

搜索資源 注冊|登陸

等待

返回 展開菜單
按功能 按軟件

unity3d視頻教程

unity3d視頻教程

包含11節(jié)視頻教程

從零基礎(chǔ)學習unity3d游戲引擎,簡單易學的視頻教程,讓你快速掌握unity3d,并喜歡上游戲開發(fā)的樂趣。

關(guān)閉

Unity3d時間、計時管理器簡介

關(guān)注:869 留言:0 樓主:路絲絲 發(fā)帖時間:15年11月2日

路絲絲

普通會員

路絲絲

社區(qū)兄弟:4級

關(guān)注4365人

  • 積分

    97

  • 登陸

    11

  • 發(fā)帖

    39

  • 留言

    5

  • 作品

    1

間隔線

在之前文章我們提到過定時器的做法《unity教程-自定義Clock定時器類 》,在平時的游戲開發(fā)過程中,我們或多或少的會用到時間類,比如技能的冷卻時間,角色的生命回復等等都會用到,而處理方式也有很多種,我們可以在每個技能上面掛載一個時間類,也可以提供一個時間管理器,來統(tǒng)一管理技能的冷卻,個人推薦第二種做法,因為這樣會更加精準!

時間管理器的類主要包括 TimerManager.cs,代碼如下:

using Unity Engine;

using System;

using System.Collections.Generic;

///

/// 移動管理

///

public class TimerManager

{

public static float time;

public static Dictionary timerList = new Dictionary();

public static void Run()

{

// 設置時間值

TimerManager.time = Time.time;

TimerItem[] objectList = new TimerItem[timerList.Values.Count];

timerList.Values.CopyTo(objectList, 0);

// 鎖定

foreach(TimerItem timerItem in objectList)

{

if(timerItem != null) timerItem.Run(TimerManager.time);

}

}

public static void Register(object objectItem, float delayTime, Action callback)

{

if(!timerList.ContainsKey(objectItem))

{

TimerItem timerItem = new TimerItem(TimerManager.time, delayTime, callback);

timerList.Add(objectItem, timerItem);

}

}

public static void UnRegister(object objectItem)

{

if(timerList.ContainsKey(objectItem))

{

timerList.Remove(objectItem);

}

}

}

TimerItem.cs,代碼如下:

using UnityEngine;

using System;

public class TimerItem

{

///

/// 當前時間

///

public float currentTime;

///

/// 延遲時間

///

public float delayTime;

///

/// 回調(diào)函數(shù)

///

public Action callback;

public TimerItem(float time, float delayTime, Action callback)

{

this.currentTime = time;

this.delayTime = delayTime;

this.callback = callback;

}

public void Run(float time)

{

// 計算差值

float offsetTime = time - this.currentTime;

// 如果差值大等于延遲時間

if(offsetTime >= this.delayTime)

{

float count = offsetTime / this.delayTime - 1;

float mod = offsetTime % this.delayTime;

for(int index = 0; index < count; index ++)

{

this.callback();

}

this.currentTime = time - mod;

}

}

}

測試用例代碼如下:

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

public class Demo : MonoBehaviour

{

public GameObject roleObject;

void Awake()

{

TimerManager.Register(this, 0.3f, ()=>

{

Debug.Log("0.3 -> " + System.DateTime.Now.ToString("hh:mm:ss.fff"));

});

TimerManager.Register(this.gameObject, 1f, ()=>

{

Debug.Log("1 -> " + System.DateTime.Now.ToString("hh:mm:ss.fff"));

});

}

void Update()

{

TimerManager.Run ();

}

}

好了,本篇unity3d教程到此結(jié)束,下篇我們再會!

資源地址: http://cg.silucg.com/dongman/unity3d/7981.html (分享請保留)


贊0 踩0

未知用戶

2005-2024 朱峰社區(qū) 版權(quán)所有 遼ICP備2021001865號-1
2005-2024 ZhuFeng Community All Rights Reserved

VIP

朱峰社區(qū)微信公眾號

回頂部

1.復制文本發(fā)給您的QQ好友或群、微信等;好友點擊鏈接以后,轉(zhuǎn)發(fā)就成功了。 2.如朋友點擊您的鏈接,您需要需刷新一下才行;同一個好友僅能點擊一次。
購買VIP,觀看所有收費教程。