Home > Software design >  Trying to destroy the object collided with bullet in Unity 2D
Trying to destroy the object collided with bullet in Unity 2D

Time:01-22

So I have a basic 2D game, which I shoot to random spawning enemies and kill them. I created a script that chooses a random x and y value from two points at the edge of the screen, and instantiate my enemy prefab at random positions. Here is the code for that:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    public Transform LeftScreenIdentifier;
    public Transform RightScreenIdentifier;
    public GameObject Enemy;
    public float spawnEveryXSeconds;
    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("Spawn",2.0f,spawnEveryXSeconds);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    void Spawn()
    {
        float xPos = Random.Range(LeftScreenIdentifier.position.x,RightScreenIdentifier.position.x);
        float yPos = Random.Range(LeftScreenIdentifier.position.y,RightScreenIdentifier.position.y);

        Vector2 spawnPos = new Vector2(xPos,yPos);

        Instantiate(Enemy,spawnPos,Enemy.transform.rotation);
    }
}

And I have a collider checking script, that If bullet hits enemy, It destroys it.

void OnCollisionEnter2D(Collision2D col) {
  
    if (col.gameObject.CompareTag("Enemy"))
    {
        Destroy(GameObject.FindGameObjectWithTag("Enemy"));
    }
}

The problem here is, when I shoot to an enemy, it sometimes destroys another enemy that spawned randomly. How to fix this?

Thanks for your time!

CodePudding user response:

Well FindGameObjectWithTag will find whatever is the first object in your hierarchy with that tag. This can be any one.

You rather simply want to destroy the one you collided with -> you already have the reference from the parameter

void OnCollisionEnter2D(Collision2D col) 
{ 
    if (col.gameObject.CompareTag("Enemy"))
    {
        Destroy(col.gameObject);
    }
}
  •  Tags:  
  • Related