- Home /
Mysteries of yield
public GameObject Pool (GameObject thing, float delay) {
StartCoroutine(PoolDelayed(thing, delay, 0));
return thing;
}
IEnumerator PoolDelayed (GameObject thing, float delay, int dummy) {
Debug.Log ("PoolDelayed is called.");
yield return new WaitForSeconds (delay);
Pool (thing);
}
Debug.Log (as well as the actual game) reveals that instead of waiting for delay
then proceeding, the whole coroutine is repeated every frame for the whole duration of delay
.
I've actually heard of some amount of wonkiness regarding everything around yield, but this is the first time I ever have WaitForSeconds()
do that in all the times I've been using it. Has somebody got some context to it and/or maybe a solution?
Where is the rest of the implementation that calls Pool originally?
And what does the other method called Pool that only takes a GameObject and no float do?
The other Pool() is the actual pooling function:
public GameObject Pool (GameObject thing) {
if (thing.tag == "AI") {
AI script = thing.GetComponent<AI>();
AIPools [script.poolNumber].pool.Add (thing);
}
else if (thing.tag == "Projectile") {
Projectile script = thing.GetComponent<Projectile>();
bulletPools [script.poolNumber].pool.Add (thing);
}
Disappear (thing);
thing.transform.parent = poolParent.transform;
thing.SetActive (false);
return thing;
}
And here's one of the two callers, itself called only once:
void Remove () {
battle.Disappear (gameObject);
battle.Pool (gameObject, effects[0].lifetime);
if (parent != null) {
parent.subProjectiles.Remove (this);
if (parent.subProjectiles.Count <= 0) battle.Pool (parent.gameObject, parent.effects[0].lifetime);
}
}
It's for an object pooling system.
Answer by Kiwasi · Sep 04, 2014 at 07:20 PM
You've got some weird logic happening here. You are also missing code relevant to the problem here.
The main question is where you are starting the sequence from. If you are calling either Pool () or StartCoroutine (PoolDelay()) every frame from Update you would see the behaviour you are experiencing.
This is not the normal way to code a repetitive loop in a coroutine, the normal way would be to use a while loop.
I only have it called occasionally upon removal (or "removal") of an object, as shows the code I've posted up above. $$anonymous$$ore than that, just now I tried to have Pool() skipping PoolDelayed() altogether straight to the other Pool() and no issue popped up at all.
Your answer
Follow this Question
Related Questions
Yield/OnTriggerEnter Help C# 1 Answer
C# WaitForSeconds doesn't seem to work ?? 2 Answers
(c#) Problems with yield 1 Answer
Playing footsteps with interval 1 Answer
Run Coroutine once, but finish Lerping 2 Answers