Skip to content

Instantly share code, notes, and snippets.

@samsheffield
Created September 15, 2021 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsheffield/0b4451157857c9705b19523013fc217b to your computer and use it in GitHub Desktop.
Save samsheffield/0b4451157857c9705b19523013fc217b to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyingThings : MonoBehaviour
{
// This example assumes you will use collision to destroy something. You can use the code inside of OnTriggerEnter2D as well
private void OnCollisionEnter2D(Collision2D collision)
{
// If the other thing has a specific tag. It's a good idea to limit the detection to specific things
if (collision.gameObject.CompareTag("Player") == true)
{
// Destroy this gameobject?
Destroy(gameObject);
// Destroy the gameobject this one collided with? Uncomment this next line
//Destroy(collision.gameObject);
}
}
}
Here is a bonus Unity example for 2D Game Design F21. Let me know what else you need!
======================================================================================
HOW TO DESTROY GAMEOBJECTS
Full example: DestroyThings.cs
Important:
1. Your GameObjects need colliders (set to triggers if necessary)
2. The second example assumes you're using OnCollisionEnter2D(Collision2D collision) or OnTriggerEnter2D(Collider2D collision)
// Use this to destroy this gameobject:
Destroy(gameObject)
// Use this to destroy another gameobject upon collision or trigger:
Destroy(collision.gameObject);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment