To make ball disappear

How to make the ball disappear?

The used or lunched ball is still there. So, is there any script to make it disappear or destroy?

Have you tried Destroy(ballObjectYouWantDestroyed);

You’re quite right, we’re not really dealing with those balls after they are launched. If they go off the screen, we don’t care much about them, but a look at the heirarchy shows that they’re all there, even when they go off the screen.


There are a couple of ways we can deal with this. We could continue to work off of one script, but that script is starting to get a bit messy, and it’s really more about launching the ball than dealing with the consequences of the launch.

Let’s create a new class Ball, and put it on our Ball prefab.
This class will check to see if the ball has gone off screen (OnBecameInvisible) or if the ball is involved in a collision (OnCollisionEnter2D).

using UnityEngine;

public class Ball : MonoBehaviour
{
    [SerializeField] float destructDelay = 5f;
    private void OnBecameInvisible()
    {
        DestroySelf();
    }
    
    private void OnCollisionEnter2D(Collision2D other)
    {
        DestroySelf();
    }

    void DestroySelf()
    {
        Destroy(gameObject, destructDelay);
    }
}

You can fine tune the destructDelay to taste (I found 5 to be about right).

2 Likes

Privacy & Terms