Detecting Collisions with OnCollisionEnter

Checked with version: 4.1

-

Difficulty: Beginner

How to detect collisions between objects in code using the OnCollisionEnter function.

Detecting Collisions with OnCollisionEnter

Beginner Physics

Transcripts

DestroyCubes

Code snippet

using UnityEngine;
using System.Collections;

public class DestroyCubes : MonoBehaviour
{
    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name == "prop_powerCube")
        {
            Destroy(col.gameObject);
        }
    }
}
#pragma strict

function OnCollisionEnter (col : Collision)
{
    if(col.gameObject.name == "prop_powerCube")
    {
        Destroy(col.gameObject);
    }
}
import UnityEngine
import System.Collections


public class DestroyCubes(MonoBehaviour):

    private def OnCollisionEnter(col as Collision):
        if col.gameObject.name == 'prop_powerCube':
            Destroy(col.gameObject)
Physics Joints
Raycasting

Related tutorials

Related documentation

Got it

We’ve updated our Terms of Service and software agreement to reflect recent changes to our business model. We’ve also updated our Privacy Policy to better reflect our current data collection and use practices.

We use cookies to ensure that we give you the best experience on our website. Click here for more information.