禁用游戏对象,但继续运行协程



我有一个BonusController脚本作为Bonus游戏对象的组件。此奖励必须在碰撞时被摧毁,但必须"行动"几秒钟。我已经为此启动了一个协程,但脚本停止执行(我认为这是因为我将游戏对象设置为非活动状态(。这是BonusController的代码:

void OnTriggerEnter2D(Collider2D col)
{
    StartCoroutine(speedUp(1));
    gameObject.SetActive(false);
}
IEnumerator speedUp(float seconds)
{
    Debug.Log("before");
    yield return new WaitForSeconds(seconds);
    Debug.Log("after"); // <--- This is never called
}

如何删除对象而不停止协程脚本执行?

你不能禁用mesh renderercollider吗?这样,游戏对象仍将存在,但用户将无法看到它。

你不能拉你站立的地面。 :)

只需在使用 2D 方法时禁用SpriteRenderer即可。并保持对象活动并启用。

{
    StartCoroutine(speedUp(1));
    //gameObject.SetActive (false);
    GetComponent<SpriteRenderer> ().enabled = false;
    GetComponent<Collider2D> ().enabled = false;
    // Above line will deactivate the first collider it will find.
}
IEnumerator speedUp(float seconds)
{
    Debug.Log("before");
    yield return new WaitForSeconds(seconds);
    Debug.Log("after"); // <--- This is never called
}

为了在一段时间后销毁对象,请在屈服后在协程内调用销毁。

yield return WaitForSeconds(second);
Destroy(this);

现在它被适当地销毁了,并将释放内存,而不是仍然存在,看不见,但占用资源。

最新更新