Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Top Down Shooter Bullets Not Deleting

So far my code looks like this:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Bullet : MonoBehaviour

{

   public GameObject hitEffect;

   

   void OnCollisionEnter2D(Collision2D collision)

   {

       GameObject boom = Instantiate(hitEffect, transform.position, Quaternion.identity);

       Destroy(gameObject, 0);

       Destroy(boom, 3f);

   }

}

The explosion disappears like stated, but the bullet does not delete after a while. I gave the bullet the same delay as the explosion to see what happens to the bullets that where connected to the explosion and they deleted after a while. The bullets not connected to the explosion did not do the same. Even though it is stated in the code for the bullet to be destroyed. I even tried to a WaitForSeconds command, which did nothing but make errors. Can someone please help.

Best Answer

  • MTCMTC Member
    Accepted Answer

    I found a solution! I used a different tutorial on shooters that lead to this line of code:

    void Update()

       {

           Timer -= Time.deltaTime;

           if(Timer <= 0)

           {

               Destroy(gameObject);

           }

       }

    which had a Public Float variable called timer. I found that the problem was that the line of code was only getting triggered when it got in contact with a collider. This line of code deals with bullets not getting in contact with colliders. This came to mind from a different Youtuber called quill18creates.

Answers

  • macca7000macca7000 Member
     void OnCollisionEnter2D(Collision2D collision)
       {
           GameObject boom = Instantiate(hitEffect, transform.position, Quaternion.identity);
           Destroy(gameObject, 0);
           Destroy(boom, 3f);
       }
    

    Normally you need a "f" after the 0, so unity doesn't get confused between integers and floats.

    But the code from your first post is fine just change :

    Destroy(gameObject, 0);
    

    Change to :

    Destroy(gameObject);
    

    

Sign In or Register to comment.