Auto-destroying the bullet

As we have mentioned, we would like to destroy the bullet after a certain time specified by the timeBeforeDestruction variable. Unity comes with a built-in function to destroy a game object after a delay, and once again the Start() function is the perfect place for such a thing. In fact, we just need to specify the game object to destroy (in this case the bullet itself), and the time. So, the Start() function at the end should be like the following:

    void Start() { 
        rigidBody = GetComponent<Rigidbody2D>(); 
 
        //Destroy the bullet if it didn't hit anything after 10 seconds 
        Destroy(gameObject, timeBeforeDestruction); 
    } 

If you were to place a bullet in the scene now and hit play, it would be destroyed after ten seconds, which is the default value for the timeBeforeDestruction variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset