简体   繁体   English

统一的游戏对象计时器

[英]Gameobject​ timer in unity

我正在尝试制作一个有游戏对象(假设是一个球)的统一游戏,并且在分配的时间(5 秒)之后游戏对象消失了,代码中有任何线索吗?

The simplest way to achieve that is to use Unity's built-in Destroy() method.实现这一目标的最简单方法是使用 Unity 的内置Destroy()方法。
You can pass your object and a timer (in seconds) as arguments.您可以将对象和计时器(以秒为单位)作为参数传递。

Destroy(gameObject, 5); // destroys the gameObject after 5 seconds elapsed

Well, you could try to use the Invoke method, which will call the method you specify after some time.好吧,您可以尝试使用 Invoke 方法,它会在一段时间后调用您指定的方法。

void Start()
{
    Invoke("DestroyMyObject", 5);
}

void DestroyMyObject()
{
    this.Destroy(this.gameObject);
}

If you want to call some method repeatedly, you could use InvokeRepeating Here is the whole documentation:如果你想重复调用某个方法,你可以使用 InvokeRepeating 这里是整个文档:

Invoke docs调用文档

InvokeRepeating docs 调用重复文档

You can use an coroutine for the timer.您可以为计时器使用协程。 This is a bit more complicated than other answers, but it is good practice for using coroutines.这比其他答案要复杂一些,但这是使用协程的好习惯。 For example:例如:

IEnumerator DestroyObject(GameObject object, int time) {
yield return new WaitForSeconds(time);
Destroy(object);
}

If this script is attached to a controller or anything else that isn't the player:如果此脚本附加到控制器或其他任何不是玩家的东西:

public GameObject player;

//Wherever the player is supposed to be destroyed 
{
DestroyObject(player, 5);
}

If this script is attached to the player:如果此脚本附加到播放器:

//Wherever the player is supposed to be destroyed
{
DestroyObject(this.gameObject, 5);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM