Coroutine from Callback doesn't handle yield returns.
Hows it going,
I am currently working on a modular 'item' powerup system using some delegate methods.
From this base class
using UnityEngine;
using System.Collections;
public class Item : MonoBehaviour {
public delegate void Execute();
public Execute executor;
public Mesh mesh;
public Texture2D texture;
public Character controller;
void Start (){
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshRenderer>().material.SetTexture("_MainTex", texture);
}
//This will be called by the character when the character collides with this object
//TODO remember that you can access this class even if a subclass is attatched. E.G. just getting this component will suffice
//TODO even if a subclass is attatched not this class
public void execute(){
Destroy(this);
executor();
}
}
I then extend that from other classes such as
using UnityEngine;
using System.Collections;
public class Slow : Item {
// Use this for initialization
void Awake () {
this.executor = slowPlayer;
}
public void slowPlayer(){
print("starting!");
StartCoroutine("slowForThree");
}
IEnumerator slowForThree(){
Time.timeScale = 0.5f;
yield return new WaitForRealSeconds(4);
Time.timeScale = 1f;
yield break;
}
}
But when I try and call a coroutine as seen above, it starts the coroutine, but never finishes it, once it reaches a yield statement, it just stops. I cannot figure out why, and I am wondering if this might be a bug. Anyway, has anybody had this problem and if so, how did you fix it.
Thanks!
try ths :
public void execute()
{
StartCoruotine("WaitTime");
executor();
}
public IEnumerator WaitTIme()
{
yield return new WaitForRealSeconds(required time);
destroy(gameobject);
}
Answer by mj321 · Aug 27, 2016 at 09:25 AM
public void execute(){
Destroy(this);
executor();
}
When you destroy the object all its coroutines will be stopped, too. Try destroying it after the coroutine has finished.
Wow thanks, this was a complete oversight on my behalf, I don't even remember writing that! Thanks for pointing it out!
Answer by Konsicrafter · Aug 27, 2016 at 02:29 PM
I would replace StartCoroutine("slowForThree");
with StartCoroutine(slowForThree());
, this works better for me. Why are you using WaitForRealSeconds? I think it would be better to use WaitForSeconds and maybe multiply it with 2 because of the timeScale. I don't know why you are using yield break
, you do not need that, the IEnumerator finishes after the last codeline in it itself.