- Home /
Invoke a Coroutine From OnCollisionEnter
Hi, it seems that the 'yield return StartCoroutine' in OCE does not act properly when being invoked from the OnCollisionEnter() Method:
public class example : MonoBehaviour {
public GameObject instPrefab;
public Effects e;
public void Start() {e = Effects.CreateInstance<Effects>();}
public IEnumerator OnCollisionEnter(Collision col) {
Debug.Log("Collided!"); //<--happens
ContactPoint cp = col.contacts[0];
Vector3 pos = cp.point;
if (instPrefab) {
yield return StartCoroutine(e.ParticleEffects(instPrefab, pos));
Debug.Log("Done with Coroutine"); //Never happens
}
}
}
public class Effects : ScriptableObject { public IEnumerator ParticleEffects(GameObject instPrefab, Vector3 pos) {
Debug.Log("Starting Co-Routine"); // <-Happens
GameObject inst = (GameObject) Instantiate(instPrefab, pos, Quaternion.identity);
ParticleEmitter pE = inst.GetComponent<ParticleEmitter>( );
while (pE.maxSize > 0) {
pE.maxSize -= 5 * Time.deltaTime;
yield return null; // return a null frame?
}
Debug.Log("End"); // <-- Still Does not happen
}
}
Is their something that I am missing? Or am I just unable to do this after the method OCE is invoked? Again, the problem $is not being able to Wait for a desired amount of seconds in the Coroutine, "ParticleEffects"
I suppose the question may now be, what is attached to what?
where do you set your "instPrefab" ? because it's private... (should be public?) are you even sure that you reach the yield statement? Debug.Log before this line, maybe there went something else wrong.
ehm, did you write this example without testing? Because ContactPoint don't have .contacts[] only .point. And you should make a block after "if (instPrefab)" and include your Debug.Log to see if your prefab is set properly. And the Effects class needs one more "}"
:D np, I've tried your code and it works... don't know what's wrong. Do you even get a collision? ps. You changed the code in Particle Effects() but you removed the inst before GetComponent ;) Just a little hint: if nothing works just put after every single line a Debug.Log and watch carefully what is executet and what is not
Do you use 2 seperate files for the "example" script and your "Effects" script? Because a ScriptableObject have to be in it's own file (filename equals classname). Try to put a Debug.Log after each line of code and watch how far you come.
Answer by Eric5h5 · Jan 15, 2011 at 02:52 AM
OnCollisionEnter itself can be a coroutine; you don't need to call another coroutine from it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613095534im_/https://answers.unity.com/themes/thub/images/avi.jpg)