Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity C# StartCoroutine() in Destroyed Object

I have this script in Unity with C# and the time of the Coroutine not working, second line with forwardForce = 10f has not been called :

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());
  }

}
like image 341
Ciuca Cristi Avatar asked Apr 13 '26 14:04

Ciuca Cristi


2 Answers

You are destroying the GameObject hosting the coroutine, which will destroy the coroutine causing it not to finish. You will want to destroy the GameObject at the end of the coroutine, or use a static coroutine manager.

like image 111
hanoldaa Avatar answered Apr 15 '26 05:04

hanoldaa


It's probably not the cleanest way, but if really you want to destroy this game object it's not so easy:

private IEnumerator DecreaseSpeed ()
{
    GameObject.Find("Player").GetComponent<PlayerMovement>().forwardForce = 1f;
    Thread.Sleep(2000);
    GameObject.Find("Player").GetComponent<PlayerMovement>().forwardForce = 10f;
}

But better way is to inject calss to SlowPickup, that handle this coroutine

private TimeClass ts;

void Start ()
{
    ts = ...; //Inject
}

void OnTriggerEnter ()
{
    ts.RunCoroutine(); //Implement logic in TimeClass
    Destroy(gameObject);
}

It's should work.

like image 27
Wojciech Rak Avatar answered Apr 15 '26 04:04

Wojciech Rak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!