我在Unity中使用C#编写了此脚本,并且协程的时间不起作用,未调用forwardForce = 10f
的第二行
:
using UnityEngine;
using System.Collections;
public class SlowPickup : MonoBehaviour
{
public float waitTime = 2f;
private IEnumerator DecreaseSpeed ()
{
GameObject.Find("Player").GetComponent<PlayerMovement>().forwardForce = 1f;
yield return new WaitForSeconds(waitTime);
GameObject.Find("Player").GetComponent<PlayerMovement>().forwardForce = 10f;
}
void OnTriggerEnter ()
{
Destroy(gameObject);
StartCoroutine(DecreaseSpeed());
}
}
答案 0 :(得分:4)
您正在破坏托管协程的GameObject,这将破坏协程,导致协程不完成。您将要在协程结束时销毁GameObject,或使用静态协程管理器。
答案 1 :(得分:1)
这可能不是最干净的方法,但是如果您真的想销毁这个游戏对象,那就不是那么容易了:
private IEnumerator DecreaseSpeed ()
{
GameObject.Find("Player").GetComponent<PlayerMovement>().forwardForce = 1f;
Thread.Sleep(2000);
GameObject.Find("Player").GetComponent<PlayerMovement>().forwardForce = 10f;
}
但是更好的方法是将calss注入处理这种协程的SlowPickup
private TimeClass ts;
void Start ()
{
ts = ...; //Inject
}
void OnTriggerEnter ()
{
ts.RunCoroutine(); //Implement logic in TimeClass
Destroy(gameObject);
}
应该可以。