[GitHub] - Unity Timer
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:
- Use a coroutine with the WaitForSeconds method.
- Store the time that your timer started in a private variable (e.g.
startTime = Time.time), then check in an Update call ifTime.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
- This library does not currently seem to work on the Hololens. We are looking into a solution for this.
- 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的更多相关文章
- 搜刮一些开源项目的APP
iOS完整App资源收集 <iOS完整app资源收集> <GitHub 上有哪些完整的 iOS-App 源码值得参考?> <GitHub 上有哪些完整的 iOS-App ...
- Unity时钟定时器插件——Vision Timer源码分析之一
因为项目中,UI的所有模块都没有MonBehaviour类(纯粹的C#类),只有像NGUI的基本组件的类是继承MonoBehaviour.因为没有继承MonoBehaviour,这也不能使用Updat ...
- UNITY中有Timer
using UnityEngine; using System.Collections; using System.Timers; public class NewBehaviourScript : ...
- Unity时钟定时器插件——Vision Timer源码分析之二
Unity时钟定时器插件——Vision Timer源码分析之二 By D.S.Qiu 尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com 前面的已经介绍了vp_T ...
- Unity Github 项目收集
http://gad.qq.com/article/detail/24048 重磅推荐: Github 热门 Unity Assets 查询:http://unitylist.com/browse 最 ...
- 最棒的Unity Github 项目收集(2016)
http://1darray.com/blog/2016/03/08/best-unity-github-repositories/ List of best public GitHub reposi ...
- 【Unity】制作简易定时器(Timer)
最近开始学习Unity,也想开始学习写一些简单的博客. 在网上学习了一些关于定时器的写法,在此简单总结一下,方便自己以后用到时查阅. 需求:制作定时器,运行3秒后执行第一次,之后每隔3秒执行一次操作. ...
- dynamic bone unity github
https://github.com/unity3d-jp/unitychan-crs 我发现我总找不到以前的东西.. https://www.cnblogs.com/alps/p/8284577.h ...
- github for unity
随机推荐
- UITableView的plain样式下,取消区头停滞效果
核心代码 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat sectionHeaderHeight = sectionH ...
- rest_framework --- viewsets
viewsets :from rest_framework import viewsets #导入方式 ViewSetMixin(object): 这个类,大致作用就是重写了as_view()方法,假 ...
- 字符串拼接在Oracle和mysql中的用法
oracle拼接字符串 1.使用 '||' 或者 concat(参数1,参数2) select 'aa' || 'bb' || 'cc' from dual; 结果:aabbcc select co ...
- MySQL 修改主键
网上顺便查了下 ,要先删除 再创建,如果是添加复合主键,则复合主键值不能为空 alter table table_name drop primary key; alter table table_na ...
- linux系统基础之---RPM管理(基于centos7.4)
- 浅谈linux系统中pdf文件的默认打开方式
atril.gimp和evince,三者均可以打开application/pdf格式文件.gimp为一款图像处理软件:atril为mate环境下常用的文档查看器:evince为gnome环境下常用的文 ...
- jquery获取周对应的日期
项目中用到按周显示的功能,找了一个,然后自己修改了一下,留着以后用: 这是代码,要是直接显示的话就把第43行去掉就行了,如果想要得到数据按照自己的想法重新渲染就保留43行,直接看51行,52行就是你要 ...
- 修改二维码生成插件jquery.qrcode.js支持加入自定义LOGO
1,将jquery.qrcode.min.js和jquery添加到您的网页中 <script src="jquery.min.js"></script> & ...
- JS基础知识-01
01-浅谈前端发展史 第一阶段:C/S(client server)->B/S(browser server) 网页制作 技术栈:PhotoShop.HTML.CSS 第二阶段:从静态到动态,从 ...
- Scala继承
override重写 为什么要用override关键字?因为这样更清楚,不容易出错,比如打错字了,就没覆盖成功,但是不会报错 override可以覆盖feild和method class Person ...