How to do somethings after collision between two objects? -- Unity -- Collision
How to do somethings after collision between two objects? -- Unity -- Collision
[Ans]
OnCollisionEnter or OnTriggerEnter func.
Suppose that when ACube object collides with Ground_Cube object, it will trigger event.
Do following steps.
Step1:
In Unity, add collider as component in ACube.
Step2:
In Unity, add collider as component in Ground_Cube.
Step3:
In Unity, add Rigidbody as component in ACube.
Step4:
Great Importance!!!
Check the setting in Rigidbody in Ground_Cube, collider in ACube and collider in Ground_Cube.
Step5:
In Script, override the OnCollisionEnter func.
public void OnCollisionEnter(Collision collision)
{
//Do something
}
[NOTE]
Great Importance!!!
(1)Unity is a case-insensitive language. i.e. In Unity, uppercase and lowercase letter are different.
onCollisionEnter is not accepted.
If you spell it wrong, the func. will be recongized as your own func.
If you do so, compiler will not throw error, but it can not work.
(2)OnCollisionEnter func. must take 1 parameter which type is Collision.
Recently, I have made the simple mistake and spend about 15 min.
I think I am a little dumb at that time.
I wrote something in OnTriggerEnter func.
more details on callback to OnCollisionEnter v.s. OnTriggerEnter func.
See on
or
more API.
(1)OnCollisionEnter
(2)OnTriggerEnter
Step6:
Great Importance!!!
In Unity, Attach the Script to ACube object
[NOTE]
Attach it to wrong object will not work.
I have made the simple mistake and spend about 15 min.
Step7:
Save and Run to check it.
Comments
Post a Comment