https://github.com/akbiggs/UnityTimer#unity-timer

Run actions after a delay in Unity3D.

This library has been battle-tested and hardened throughout numerous projects, including the award-winning Pitfall Planet.

Written by Alexander Biggs + Adam Robinson-Yu.

Installation

To get the latest release of UnityTimer, head over to the Releases page and download the Timer.unitypackage file from the latest release. Then if you have a Unity project open, you can open the .unitypackage file to install the scripts into your project.

Alternatively, if you like to live on the bleeding edge, you can clone this repository into your project's Assets folder. However, we do not guarantee this will give you a stable version.

Basic Example

The Unity Timer package provides the following method for creating timers:

/// <summary>
/// Register a new timer that should fire an event after a certain amount of time
/// has elapsed.
/// </summary>
/// <param name="duration">The time to wait before the timer should fire, in seconds.</param>
/// <param name="onComplete">An action to fire when the timer completes.</param>
public static Timer Register(float duration, Action onComplete);

The method is called like this:

// Log "Hello World" after five seconds.

Timer.Register(5f, () => Debug.Log("Hello World"));

Motivation

Out of the box, without this library, there are two main ways of handling timers in Unity:

  1. Use a coroutine with the WaitForSeconds method.
  2. Store the time that your timer started in a private variable (e.g. startTime = Time.time), then check in an Update call if Time.time - startTime >= timerDuration.

The first method is verbose, forcing you to refactor your code to use IEnumerator functions. Furthermore, it necessitates having access to a MonoBehaviour instance to start the coroutine, meaning that solution will not work in non-MonoBehaviour classes. Finally, there is no way to prevent WaitForSeconds from being affected by changes to the time scale.

The second method is error-prone, and hides away the actual game logic that you are trying to express.

This library alleviates both of these concerns, making it easy to add an easy-to-read, expressive timer to any class in your Unity project.

Features

Make a timer repeat by setting isLooped to true.

// Call the player's jump method every two seconds.

Timer.Register(2f, player.Jump, isLooped: true);

Cancel a timer after calling it.

Timer timer;

void Start() {
timer = Timer.Register(2f, () => Debug.Log("You won't see this text if you press X."));
} void Update() {
if (Input.GetKeyDown(KeyCode.X)) {
Timer.Cancel(timer);
}
}

Measure time by realtimeSinceStartup instead of scaled game time by setting useRealTime to true.

// Let's say you pause your game by setting the timescale to 0.
Time.timeScale = 0f; // ...Then set useRealTime so this timer will still fire even though the game time isn't progressing.
Timer.Register(1f, this.HandlePausedGameState, useRealTime: true);

Attach the timer to a MonoBehaviour so that the timer is destroyed when the MonoBehaviour is.

Very often, a timer called from a MonoBehaviour will manipulate that behaviour's state. Thus, it is common practice to cancel the timer in the OnDestroy method of the MonoBehaviour. We've added a convenient extension method that attaches a Timer to a MonoBehaviour such that it will automatically cancel the timer when the MonoBehaviour is detected as null.

public class CoolMonoBehaviour : MonoBehaviour {

   void Start() {
// Use the AttachTimer extension method to create a timer that is destroyed when this
// object is destroyed.
this.AttachTimer(5f, () => { // If this code runs after the object is destroyed, a null reference will be thrown,
// which could corrupt game state.
this.gameObject.transform.position = Vector3.zero;
});
} void Update() {
// This code could destroy the object at any time!
if (Input.GetKeyDown(KeyCode.X)) {
GameObject.Destroy(this.gameObject);
}
}
}

Update a value gradually over time using the onUpdate callback.

// Change a color from white to red over the course of five seconds.
Color color = Color.white;
float transitionDuration = 5f; Timer.Register(transitionDuration,
onUpdate: secondsElapsed => color.r = 255 * (secondsElapsed / transitionDuration),
onComplete: () => Debug.Log("Color is now red"));

A number of other useful features are included!

  • timer.Pause()
  • timer.Resume()
  • timer.GetTimeRemaining()
  • timer.GetRatioComplete()
  • timer.isDone

A test scene + script demoing all the features is included with the package in the Timer/Example folder.

Usage Notes / Caveats

  1. This library does not currently seem to work on the Hololens. We are looking into a solution for this.
  2. All timers are destroyed when changing scenes. This behaviour is typically desired, and it happens because timers are updated by a TimerController that is also destroyed when the scene changes. Note that as a result of this, creating a Timer when the scene is being closed, e.g. in an object's OnDestroy method, will result in a Unity error when the TimerController is spawned..

[GitHub] - Unity Timer的更多相关文章

  1. 搜刮一些开源项目的APP

    iOS完整App资源收集 <iOS完整app资源收集>  <GitHub 上有哪些完整的 iOS-App 源码值得参考?> <GitHub 上有哪些完整的 iOS-App ...

  2. Unity时钟定时器插件——Vision Timer源码分析之一

    因为项目中,UI的所有模块都没有MonBehaviour类(纯粹的C#类),只有像NGUI的基本组件的类是继承MonoBehaviour.因为没有继承MonoBehaviour,这也不能使用Updat ...

  3. UNITY中有Timer

    using UnityEngine; using System.Collections; using System.Timers; public class NewBehaviourScript : ...

  4. Unity时钟定时器插件——Vision Timer源码分析之二

      Unity时钟定时器插件——Vision Timer源码分析之二 By D.S.Qiu 尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com 前面的已经介绍了vp_T ...

  5. Unity Github 项目收集

    http://gad.qq.com/article/detail/24048 重磅推荐: Github 热门 Unity Assets 查询:http://unitylist.com/browse 最 ...

  6. 最棒的Unity Github 项目收集(2016)

    http://1darray.com/blog/2016/03/08/best-unity-github-repositories/ List of best public GitHub reposi ...

  7. 【Unity】制作简易定时器(Timer)

    最近开始学习Unity,也想开始学习写一些简单的博客. 在网上学习了一些关于定时器的写法,在此简单总结一下,方便自己以后用到时查阅. 需求:制作定时器,运行3秒后执行第一次,之后每隔3秒执行一次操作. ...

  8. dynamic bone unity github

    https://github.com/unity3d-jp/unitychan-crs 我发现我总找不到以前的东西.. https://www.cnblogs.com/alps/p/8284577.h ...

  9. github for unity

随机推荐

  1. chromium之tracked_objects

    // For each thread, we have a ThreadData that stores all tracking info generated // on this thread. ...

  2. round函数在oracle和mysql中用法

    1.oracle和mysql通用方法 #round(字段1,小数位数) 四舍五入select round('11.123456',4);结果:11.1235 2.mysql的另外2种保留小数位数方法# ...

  3. Sonar安装-Linux[20171227]

    前言     一款不错的代码质量管理工具Sonar 前期准备     官方参考文档 https://docs.sonarqube.org/display/SONAR/Documentation     ...

  4. hibernate的CRUD操作

    一对多关系映射的crud操作: 1.单项的保存操作 /** * 保存操作 * 正常的保存:创建一个联系人,需要关联客户 */ @Test public void test1(){ Session s= ...

  5. MySql指令的执行顺序

    1:From 2:On 3:Join 4:Where 5:Group by 5.1:函数 6:Having 7:Select 8:Distinct 9:Order by

  6. js中面向对象(创建对象的几种方式)

    1.面向对象编程(OOP)的特点: 抽象:抓住核心问题 封装:只能通过对象来访问方法 继承:从已有的对象下继承出新的对象 多态:多对象的不同形态 一.创建对象的几种方式 javascript 创建对象 ...

  7. Apache Maven(四):依赖

    依赖管理是Maven的特性之一,它是用户最为熟悉的特性之一,也是Maven擅长的领域之一.管理单个项目的依赖并没有太大困难,但是当您开始处理由数十或数百个模块组成的多模块项目和应用程序时,Maven可 ...

  8. go 操作数据库

    假设有了数据库,创建表 CREATE TABLE `userinfo` ( `uid` INT(10) NOT NULL AUTO_INCREMENT, //自增字段 `username` VARCH ...

  9. UVA11988 Broken Keyboard (a.k.a. Beiju Text)【数组模拟链表】

    参考:https://blog.csdn.net/lianai911/article/details/41831645 #include <iostream> #include <c ...

  10. 2018徐州网络赛H. Ryuji doesn't want to study

    题目链接: https://nanti.jisuanke.com/t/31458 题解: 建立两个树状数组,第一个是,a[1]*n+a[2]*(n-1)....+a[n]*1;第二个是正常的a[1], ...