Destroy and Re-Instantiate objects when they are out of camera

So I basically want to destroy objects when they are out of the camera but I re-instantiate it when the object can be seen by the camera again, I can’t think of a performant way to do this, thanks in advance for any answer :smile:

Well, I think thats not a good idea since Unity doesn’t graph objects outside of camera automatically (unless you unset the option). Since you say u want to reinstantiate it, I assume it’s an static object with no movement or any AI, since you also will destroy any scipt attached to it.

A most common practice is, instead of destroy and instantiate all the objects. Make the same with a pool of objects. If the game is lineal, you can Destroy/Instantiate it when player makes an event, if it’s an open world, you would need to see the transform.position and the transform.position of your camera… or if the gameObject has some Renderer:

    private void OnBecameInvisible()
    {
        Debug.Log("I'm invisible");
    }

    private void OnBecameVisible()
    {
        Debug.Log("I'm here");
    }

But remember, if you destroy the gameObject OnBecameInvisible(), he will not be able to became visible again

1 Like

Thanks for the quick answer, I already tried setting my objects active/deactivating them using these methods, deactivating worked, but reactivating didn’t since the object is deactivated and can’t interact with the script, do you know a workaround for this?

Well if you wanna do it with OnBecame(In)Visible functions, attach each GameObject you wanna to deactivate as a child of a parent called, for example, Deactivator. And Deactivator would have this script attached.

public class Deactivator : MonoBehaviour
{
    GameObject target;

    void Awake()
    {
        target = transform.GetChild(0).gameObject;
    }

    private void OnBecameInvisible()
    {
        target.SetActive(false);
    }

    private void OnBecameVisible()
    {
        target.SetActive(true);
    }
}

And you would deactivate the whole GameObject, just keeping the parent which only has attached the script for reactivate it. But as I listened to (I’m not sure about this, never test what works better) the pool system I talked at the post above is a better practice.

1 Like

thanks that helped, and sorry that it took so long to reply :smile: