Hello, I am new to Unity so please be patient with me. I am trying to create a game where you have objects moving across the screen and your player character shoots projectiles. I want to make it so if the projectile hits the enemy object, the shot and the enemy will be destroyed. On both objects I used a rigid body and I gave the enemy a tag, “Enemy”. In the code for the shot, I am trying to use the onCollisionEnter2D function and have it search for the object by tag. It then calls DestroyObject to destroy the shot. The code is not working as the shot passes through the enemy object. I am wondering if anyone can help me figure out a solution? The code for the shot is below.
using UnityEngine;
using System.Collections;
public class ShotScript : MonoBehaviour
{
//public int damage = 2;
public GameObject shot;
public bool isEnemyShot = false;
void Start()
{
}
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.tag == "Enemy") {
DestroyObject(shot.gameObject);
}
}
}
1)If that script is a component of your shot then just:
Destroy(gameObject);
2)If it is not then:
Destroy(shot);
Now also make sure for both cases that your Enemy indeed have an “Enemy” tag. In order to make sure that line of code runs you can always do something like:
if (other.gameObject.tag == "Enemy")
{
Debug.Log("Found enemy");
}
Also if it is the case #2 make sure that your shot is actually your shot, something like:
if (other.gameObject.tag == "Enemy")
{
if (shot != null) Debug.Log(shot.name);
}