我想在游戏中创建一个奖励对象。当玩家拿起它时,计时器应该启动。
public void OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
StartTimer();
}
}
public void StartTimer(){
}
这里有很多解决方案!这在一定程度上取决于你的需求。在你的情况下,最喜欢的可能是
您可以使用Coroutine
public void OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
StartCoroutine (Timer());
}
}
private IEnumerator Timer()
{
yield return new WaitForSeconds (3f);
// Something that happens after 3 seconds
}
您可以直接将碰撞消息本身转换为Coroutine
public IEnumerator OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
yield return new WaitForSeconds (3f);
// Something happens after 3 seconds
}
}
或者您可以使用Invoke
在延迟后执行方法
public void OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
Invoke(nameof(AfterDelay), 3f);
}
}
public void AfterDelay()
{
// Something happens after 3 seconds
}
查看更多选项和详细信息如何在unity 中以简单的方式使脚本等待/睡眠
如果启动计时器是指例如倒计时显示,那么你肯定应该使用类似的Coroutine
public Text text;
private Coroutine timer;
public void OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
if(timer == null) timer = StartCoroutine (Timer(3f));
}
}
public void OnCollisionExit2D(Collision2D col) //player left bonus before timer passed
{
if (col.gameObject.name == "Cube")
{
if(timer == null) StopCoroutine (timer);
timer = null;
}
}
private IEnumerator Timer(float durationInSeconds)
{
var timeLeft = duration;
while(timeLeft >= 0)
{
Text.text = timeLeft.ToString(F2);
yield return null;
}
// Something that happens after the timer reached 0
Debug.Log("Hello!");
}
- Unity的方法是协同程序
public void OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
StartCoroutine(MyTimer());
}
}
IEnumerator StartTimer(){
yield return new WaitForSeconds(3f);
// DO STUFF AFTER 3 SECONDS
}
- 您可以创建一个RunDelayed帮助程序来简化语法。到目前为止我最喜欢的。它使代码看起来更干净。阅读我关于这一点的博客文章,以及如何在所有的单行为中(通过继承或扩展方法(访问它
public void OnCollisionEnter2D(Collision2D col) //player collide with bonus
{
if (col.gameObject.name == "Cube")
{
RunDelayd(3f, () => {
// DO STUFF HERE AFTER 3 SECONDS
});
}
}
protected IEnumerator DelayedCoroutine(float delay, System.Action a)
{
yield return new WaitForSeconds(delay);
a();
}
protected Coroutine RunDelayed(float delay, System.Action a)
{
return StartCoroutine(DelayedCoroutine(delay, a));
}
- 您可以使用C#任务和后台线程。在Unity中,我尽量避免使用它们,因为它们与WebGL不兼容,你可能会在玩家中遇到问题。我知道谷歌的Firebase使用它们,所以对于更复杂的异步任务,值得一看。对于你的简单案例,我不推荐他们