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());
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With