- Home /
Game Object not destroying using findwithgametag
I have a script 'shoot' attached to a player. I need to destroy the projectile tagged bullet when it collides with the gameobject tagged 'Destroyer'. But it doesn't happen. Thanks.
public class Shoot : MonoBehaviour {
public GameObject projectile;
public Vector2 velocity;
bool canShoot= true;
public Vector2 offset = new Vector2(0.4f,0.1f);
public float cooldown = 1f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0) && canShoot) {
GameObject go = (GameObject)
Instantiate (projectile,(Vector2)transform.position + offset * transform.localScale.x, Quaternion.identity);
go.GetComponent<Rigidbody2D> ().velocity = new Vector2 (velocity.x * transform.localScale.x, velocity.y);
GetComponent<Animator> ().SetTrigger ("Shoot");
StartCoroutine (CanShoot());
}
}
IEnumerator CanShoot()
{
canShoot = false;
yield return new WaitForSeconds (cooldown);
canShoot = true;
}
void OnTriggerEnter2D(Collider2D bam){
if (bam.gameObject.tag == "Destroyer") {
Destroy (GameObject.FindWithTag("Bullet"));
}
}
}
Answer by shadowpuppet · Oct 25, 2017 at 07:37 PM
I destroy my bullets by having a script on the actual instantiated prefab bullet.
OnTriggerEnter()
{
if(gameObject.Tag == "Destroyer")
Destroy (gameObject);
}
}
Thank you! I don't know why I didn't think of this before.
Answer by Devastadus · Oct 25, 2017 at 05:49 PM
I the problem is you are calling your onTiggerEnter2D from your shoot script. Which has no indication what your bullets are colliding with. Your shoot script can only detect object that collide to your shoot script.
You would want a script on your Destroyer objects that call OnTriggerEnter2D to detect when there is collisions with those. So Create another script on your destroyer scripts like for example
public class DestroyBullets : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D bam)
{
if (bam.gameObject.tag == "bullet")
{
Destroy(gameObject);
}
}
}
to destroy bullets
Your answer
![](https://koobas.hobune.stream/wayback/20220612141823im_/https://answers.unity.com/themes/thub/images/avi.jpg)