有更好的方式来等待秒吗



我是c#编程的新手,但我按照文档在代码中插入了一个等待。问题是,它似乎不起作用。这是代码:

void Start()
{
StartCoroutine(Fixed());
}
IEnumerator Fixed()
{
print("fixed clone");
yield return new WaitForSeconds(5);
Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
Rigidbody clone = Instantiate(original, originalPosition, transform.rotation);
clone.velocity = rb.velocity * speed;
}

(这只是代码的一个片段。(在Unity中,当我播放时,克隆会迅速出现,每个克隆都会在我的控制台中显示"固定克隆"消息,所以我知道它来自这里。

如果你需要整个代码来解决这个问题,我也可以插入它。

查看您的代码,您只想在延迟后生成一个对象。你真的不需要一个科罗廷来做这件事。推论非常适合在多个帧上或逐帧操作对象。

要在延迟后简单地运行函数,请尝试Invoke方法:

void Start()
{
Invoke("SpawnClone", 5.0f); //Call SpawnClone 5 seconds after start
}
void SpawnClone()
{
print("fixed clone");
Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
Rigidbody clone;
clone = Instantiate(original, originalPosition, transform.rotation);
clone.velocity = rb.velocity * speed;
}

或者尝试将其触发为Coroutine

private IEnumerator coroutine;
void Start()
{
coroutine = SpawnClone(5.0f);
StartCoroutine(coroutine); //Trigger SpawnClone coroutine and pass in the delay of 5 seconds
print("Triggered Coroutine SpawnClone");
}
private IEnumerator SpawnClone(float delay)
{
print("Coroutine tick");
yield return new WaitForSeconds(delay);
print("Coroutine logic stared: " + Time.time + " seconds");
Vector3 originalPosition = new Vector3(Random.Range(-5f, 5f), Random.Range(-2, 2), 100);
Rigidbody clone;
clone = Instantiate(original, originalPosition, transform.rotation);
clone.velocity = rb.velocity * speed;   
print("Coroutine ended: " + Time.time + " seconds");     
}

最新更新