How to destroy an object when the player touches it

Hi guys!

I am new to Unity and C# coding and currently I am building a 2D game and what I’m trying to do is when the player touches an game object(i.e. a box), the game object should be destroyed.
I have the following code for this :

void OnTriggerEnter(Collider collider) 
		if(collider.gameObject.tag == "Player")
			// destroy this object

It is working only partially. When the player touches the box, he can get through it ,and it is not removed from the hierarchy and the object texture will not dissapear(I think the object is not removed at all).
I know I’m missing something. Could you tell me what I did wrong and what should I do to repair the wrong ?


Hi, is this script attached to the player or to the GameObject?

If it is on the Player you should find the tag of the GameObject instead of the player like so: if(collider.gameObject.tag == "tag of the box")

If it is attached to the GameObject you should destroy the current GameObject and not the collided object, so use: Destroy (gameObject);

Also make sure you added the tags to your Player/GameObject

Hi @cristiensen !

Make sure this script is attached to the object you want to destroy and that the collider is marked as trigger.

Is the player supposed to be able to walk through the object? If not I’d recommend using onCollisionEnter instead.

Right now it seems this script is receiving a collision and then checking if it was the player. It then proceeds to delete the object it collided with ( Destroy(collider.gameObject) ). In this case that would be the player.

If the player is not supposed to walk through the object, make sure the collider is NOT marked as trigger and then move this script and attach it to the player instead. Make sure to update the check with a new tag. Then create a custom tag (With the same name as your check) and apply it to every destroyable object. This way you’ll have way less scripts running.

For example:

void OnCollisionEnter(Collision col)
		if(col.gameObject.tag == "Destroyable Object")

Thanks for the code guys you helped a lot me and my friends are making a small game. so the code really helped me the “coder” with a lot of collision issues!,Thanks for sharing the code guys im making a small project with friends and this helped out alot!