Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Destroy Player doesn't work....

Discussion in 'Scripting' started by dajewa, Jun 13, 2020.

  1. dajewa

    dajewa

    Joined:
    May 31, 2020
    Posts:
    32
    Hey, I'm doing a spaceship 2d game. And I need the enemy to destroy the player when colliding with it. It worked when the bullet hit the enemy, but not now. Here's the code I did.
    Code (CSharp):
    1.         void TriggerEnter2D (Collider2D col)
    2.     {
    3.         {
    4.             if(col.gameObject.tag == ("Enemy")); //I did not forget to set the enemy tag...
    5.             {
    6.                 Destroy (col.gameObject); //Destroy the player (but it didn't work...)
    7.             }
    8.         }
    9.     }
    10. }
    11.  
    12.  
    13.  
    thank you:)
     
  2. Flynn_Prime

    Flynn_Prime

    Joined:
    Apr 26, 2017
    Posts:
    383
    The code above says if the collided object was an enemy, destroy the enemy. If this method is on your player object you're destroy should look like:

    Code (CSharp):
    1. Destroy (this.gameObject);
     
  3. dajewa

    dajewa

    Joined:
    May 31, 2020
    Posts:
    32
    It still doesn't work. Idk why...
     
  4. Flynn_Prime

    Flynn_Prime

    Joined:
    Apr 26, 2017
    Posts:
    383
    Do you have a collider on your player object? Also, for a collision to be detected one of the colliding objects must have a non-kinematic rigidbody
     
  5. bitlysub2anf

    bitlysub2anf

    Joined:
    May 8, 2020
    Posts:
    71
    IDK, I am a beginner too but fell into (kind of) this problem once. Try this script to destroy the player:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerDeathSystem : MonoBehaviour
    4. {
    5.     void OnCollisionEnter2D(Collision2D collision) //Remove the 2D if your game is 3D
    6.     {
    7.         if (collision.gameObject.tag == "Bullet") //Use the tag that destroys the player on collision
    8.         {
    9.             collision.gameObject.SendMessage("ApplyDamage", 10);
    10.             //If you want to destroy the player then:
    11.             Destroy(gameObject);
    12.             //That's it. It should work but it is untested
    13.         }
    14.     }
    15. }
     
  6. dajewa

    dajewa

    Joined:
    May 31, 2020
    Posts:
    32
    It worked, thank you guys for the reply's! :)