Collision DetectionHow To Detect Collisions in C# - Unity

Author Waldo
Published November 1, 2018

In this tutorial we discuss adding colliders on our objects so that we can detect collision within our script.

Video Walkthrough

  • 0:55 - Choosing the right collider for your environment
  • 1:05 - How a collider works
  • 1:30 - 2D and 3D colliders to use
  • 2:05 - Adding a Circle Collider 2D
  • 3:35 - Adding a Box Collider 2D
  • 4:19 - How to use isTrigger
  • 4:45 - Detecting Collision in C#
  • 6:10 - Using Instantiate to load an explosion
  • 7:00 - Destroy on Collision

Source Code for ship.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ship : MonoBehaviour {
    public GameObject explosion;

    private void OnTriggerEnter2D(Collider2D other){
        Debug.Log("hit detected");
        GameObject e = Instantiate(explosion) as GameObject;
        e.transform.position = transform.position;
        Destroy(other.gameObject);
        this.gameObject.SetActive(false);
    }
}

 

Resources

1. Mobile Joystick Tutorial
2. Keeping Objects in Bounds
3. Spawning Obstacles Tutorial

Click here to download the explosion sprite sheet used in this video.

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About