[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
随机推荐
- RL 编、解码(EncodedString、DecodedString) - iOS
开发中对文本传输或二进制传输,都需要将传输的对象进行二进制字节的转化操作,所以无异于编.解码便会经常用到的操作; 当然除了这种方式之外,还有一种常用的 Base64,此文中不具体细谈, Base64 ...
- Linux基础 ppt pptx
引言 以前写过一个讲 Linux 基础的ppt,琢磨着把它分享出来,有需要的请自取. 部分截图如下 下载地址 下载地址1
- 【windows中常用的服务概览和总结】
#IIS 1)ftp 功能:1-1)FTP地址限制: 1-2)SSL加密: 1-3)目录浏览(虚拟目录): 1-4)身份验证:(基本,匿名): 1-5)授权规则: 1-6)用户隔离:用户名目录隔离:1 ...
- php 使用当前时间点进行时间范围查询
/** * 判断是否是吃早饭时间 */ $nowtime = time(); $start = strtotime('8:30:00'); $end = strtotime('9:30:00'); i ...
- MySQL学习路线图
- python 装饰器 回顾 及练习
# 复习 # 讲作业 # 装饰器的进阶 # functools.wraps # 带参数的装饰器 # 多个装饰器装饰同一个函数 # 周末的作业 # 文件操作 # 字符串处理 # 输入输出 # 流程控制 ...
- Leecode刷题之旅-C语言/python-58.最后一个单词的长度
/* * @lc app=leetcode.cn id=58 lang=c * * [58] 最后一个单词的长度 * * https://leetcode-cn.com/problems/length ...
- idea启动spring boot无法加载或找不到主类
问题产生原因:moudle名称修改,导致项目启动不了 在Terminal界面中执行以下三个命令,我在执行第一个命令的时候报了一个找不到dependency的错误,把那个报错的dependency删了就 ...
- win10在此处打开命令cmd
Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Directory\shell\OpenCmdHere] @="在此处打开命令 ...
- TensorFlow深层神经网络常用方法
深度学习所示深层神经网络的代名词,重要特性:多层.非线性. 若只通过线性变换,任意层的神经网络模型与单层神经网络模型的表达能力没有任何区别,这是线性模型的局限性.对于线性可分的问题中,线性模型可解决, ...