Trying to come up with simple kill script

Making a very basic game and trying to come up with a very simple kill script at first i tried using some Collison detection to kill player and that worked until the collision on my bullets was killing me

public class Collision : MonoBehaviour

{  
    public GameObject player;
    private void OnTriggerEnter2D(Collider2D other) {
        Debug.Log("Congratulations");
        Destroy(player);
      

    }
}

So now im trying to make a kill script that gets the position of my enemy and player and kills my player if my enemy is on the same position as my player. I know its not the best way just want to learn what the code would look to get this done. Im a beginner at unity and a novice code so just want to learn new techniques

This is what the Collider2D data that gets passed to the OnTriggerEnter2D method is for. You didn’t offer enough information, but I will assume this script is on your enemy. In that case just modify your script like this:

public class Collision : MonoBehaviour

{
    private void OnTriggerEnter2D(Collider2D other)
    {
        GameObject player = GameObject.FindGameObjectWithTag("Player"); //Or however you get your player object here
        if (other.gameObject == player)
        {
            Destroy(player);
        }
    }
}

To build on CoraBlue’s response, using CompareTag would be a better method that doesn’t require the overhead of searching through all existing objects looking for ones with a specific tag. CompareTag allocates no memory to the heap so that makes it one of the best ways of determining if the correct object has entered the trigger.

And as said above, this can be put on the player rather than the bullet. To do so, simply change the tag to “Bullet” or whatever your bullet tag is, and destroy gameObject rather than other.gameObject. It would be more efficient to have it on the player because you’d only have one script running rather than the many that would be on multiple bullets.

    public class Collision : MonoBehaviour 
    {
        private void OnTriggerEnter2D(Collider2D other)
        {
            if (other.CompareTag ("Player"))
            {
                Destroy (other.gameObject);
            }
        }
    }

https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

Hi gcpm2002,

You may want to consider using Physics2D.Raycast

Reference:
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

https://www.youtube.com/watch?v=uDYE3RFMNzk