How to use OnCollisionEnter, OnCollisionStay and OnCollisionExit

Hi!

The following package demonstrates my problem.

TestOnCollisionEnter.unitypackage

Whenever I include OnEnable() in my script, I’m unable to respond to collision events.

I also expect to be receive collision events, while using WaitForSeconds().

The scene looks like this:

  • Two boxes collide almost immediately after the scene starts.
  • One of the boxes is falling by gravity, the other is kinetic.
  • Both boxes have a collider and a rigidbody.
  • One of the boxes have the following script.
import UnityEngine
import System.Collections

class BusyCollider (MonoBehaviour):

    // def waitAndSee() as IEnumerator:
    //     Debug.Log("waiting...")
    //     yield WaitForSeconds(2.0f)
    //     Debug.Log("done!")
    //
    // def OnEnable():
    //     StartCoroutine(waitAndSee())
 
    // def OnEnable():
    //     pass
 
    def OnCollisionEnter (other as Collision):
        Debug.Log("CollisionEnter")

My results:

  • Case 1: using the code as it is, OnCollisionEnter() gets called.
  • Case 2: if OnEnable() exists, OnCollisionEnter() does not get called.
  • Case 3: if OnEnable() starts a coroutine that waits while the boxes collide, the result is the same as in Case 2.

Why does not OnCollisionEnter() get called? Can I also expect OnCollisionEnter() to be called in Case 3?
Any help is appreciated.

Well, i dont know if you’ve read the documentation yet, but here’s some links:

OnCollisionEnter

OnCollisionStay

OnCollisionExit

Regarding the spammer, thats something you’re going to have to live with, Also you might want to look at the date and realise that its currently saturday evening (depending on your location in the world), so it is going to take a bit longer than usual to get an answer.

Also, it would help a lot if you wrote what you want your script to do, i might just be high on caffeine and sleep deprived, but all i see is an analysis of what your script does.

Welcome to UnityAnswers, hope you have a great time, and want to contribute :slight_smile:

When using boo with Unity it’s very important not to confuse tabs with spaces and the boo script templates contain tabs.

In this case, if OnCollisionEnter had less indentation than the rest, say OnEnable, then OnCollisionEnter would not be considered a part of BusyCollider leading to this confusing behaviour.

Secondly, the examples would have worked as expected, if you (I) had run them, as they are written in the question.