Collision DetectionHow To Detect Collisions in C# - Unity

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

In this video, you will learn:

  • 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

 

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.


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);
    }
}

LINK TO THIS POST

SHARE THIS POST


DISCUSSION