- Home /
[SOLVED]Coroutine method called in OnCollisionEnter() not being called for each collision on chronological order ?!
Hi,
I am using an object pool to avoid intantiate and destroy being called hundred of times during game play. Everything work's fine using the object pool to activate and deactivate object pool objects. The problem is when I use a coroutine in order to delay the deactivating of the objects at least 1 second. This coroutine is called inside OnCollisionEnter() method and if I don't call this coroutine the objects deactivate immediately when the collisions happens. The collision happens between the object pool objects and the ground and if an object falling from sky touches the ground the coroutine starts yielding for one second and gameobject.setactive(false) is exectued. Now, if there is only one object activated from object pool everything works fine and this object is deactivated after 1 second. But if there are two objects activated one after another in different times and one touches the ground suppose 0.5 seconds before the second object, the coroutine starts yielding for 1 second and after the coroutine finishes the second object gets deactivated and the first objects stays on the ground withouth being deactivated. I want the object to be destroyed on a chronological order after they touched the ground, the first after 1 second, the second after 1 second and so on.
Here you have the script I am using on the ground when collision happens: public class DeactivateObjects : MonoBehaviour {
Collision col;
void OnCollisionEnter(Collision coll)
{
if (coll.gameObject.tag == "stone")
{
col = coll;
StartCoroutine ("WaitOneSecToDeactivateTrash");
}
}
IEnumerator WaitOneSecToDeactivateTrash()
{
yield return new WaitForSeconds (1f);
col.gameObject.SetActive (false);
}
}
If anyone has encountered the same problem or knows a solution for this...tell me. :) Thank you everyone, Gerald.
Answer by ShadyProductions · Jun 02, 2017 at 05:43 PM
That's because you set your coll to a col variable u store somewhere, and then call that in your IEnumerator. which becomes the 2nd coll when the other object hits so it removes the 2nd and the first one is lost. You can fix this by passing the collider object to the IEnumerator like so:
void OnCollisionEnter(Collision coll)
{
if (coll.gameObject.tag == "stone")
{
StartCoroutine (WaitOneSecToDeactivateTrash(coll));
}
}
IEnumerator WaitOneSecToDeactivateTrash(Collision coll)
{
yield return new WaitForSeconds (1f);
coll.gameObject.SetActive (false);
}
Thank you very much for your help ShadyProductions. I am really bad at program$$anonymous$$g and you really helped me with that. ;)
Your answer
Follow this Question
Related Questions
Load Children One at a Time 1 Answer
Problem with Object Pooling and Deactivating Objects.!! 1 Answer
Powerup issue - Speed 1 Answer
Changing transform.localScale but OnCollisionEnter isn't executed 1 Answer
Invincible after collision 1 Answer