Destroy an object when out of camera view

Hi everyone, I’m developing a game in which I instantiate new backgrounds every 3 seconds. These backgrounds move rightward, and so every of them will be out of camera view after a few seconds. What I want to do is destroying them when they are out of camera view. How to do it? Thank you very much.

Using an object pool would be more optimal but you can use Renderer.isVisible to do what you want to do now.

Hi, thank you for your reply. How can I use Renderer.isVisible in my script ? Thanks a lot.

using UnityEngine;
using System.Collections;

public class RandomScrolling : MonoBehaviour {
    public GameObject[] backGrounds = new GameObject[3];
    public float seconds = 0.0f;
    private float force = 235;
    private float vectorpos = -7f;
    public float vectorpos_2 = -6.8f;
    private float delay = 0.50f;
    private float levelTime = Mathf.Round(Time.timeSinceLevelLoad);

    // Use this for initialization
    void Start()
    {
        GameObject backClone = Instantiate(backGrounds[0], new Vector3(0, 4, 1), Quaternion.identity) as GameObject;
        backClone.transform.SetParent(gameObject.transform);
        backClone.GetComponent<Rigidbody2D>().AddForce(transform.right * force);
        backClone.name = "backClone";
    }

    // Update is called once per frame
    void FixedUpdate (){
        delay = 0.50f * -Time.fixedTime;
        seconds = Time.fixedTime;

        if (delay == 0)
        {
            GameObject backClone = Instantiate(backGrounds[2], new Vector3(vectorpos, 4, 1), Quaternion.identity) as GameObject;
            backClone.transform.SetParent(gameObject.transform);
            backClone.GetComponent<Rigidbody2D>().AddForce(transform.right * force);
            backClone.name = "backClone";
        }
        if (seconds % 3 == 0 && seconds != 0)
        {
            int randomInstantiate = Random.Range(0, 2);
            GameObject backClone = Instantiate(backGrounds[randomInstantiate], new Vector3(vectorpos_2, 4, 1), Quaternion.identity) as GameObject;
            backClone.transform.SetParent(gameObject.transform);
            backClone.GetComponent<Rigidbody2D>().AddForce(transform.right * force);
            backClone.name = "backClone";
        }
    }
}

There’s two ways to do this. I instantiate objects (my Enemies) that move right to left. Once they are out of screen, I set up a Collider to destroy them. To clarify, the Collider is outside the scene and just floats to the left of everything.

public class DestroyByBoundary : MonoBehaviour {
       
    void OnTriggerExit2D(Collider2D other) {

        if (other.gameObject.name == "Enemy")
        {
        Destroy(other.transform.root.gameObject);
        }
}

People say to do Object Pooling, but my game instantiates 100s of enemies per scene. I just instantiate and destroy them. I have not had any performance issues doing this.

The other way I remember reading in one of the first Unity 2D tutorials I read:

using UnityEngine;

public class Player : MonoBehaviour
{
// The force which is added when the player jumps
// This can be changed in the Inspector window
public Vector2 jumpForce = new Vector2(0, 300);

// Update is called once per frame
void Update ()
{
// Jump
if (Input.GetKeyUp("space"))
{
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce(jumpForce);
}

// Die by being off screen
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die();
}
}

// Die by collision
void OnCollisionEnter2D(Collision2D other)
{
Die();
}

void Die()
{
Application.LoadLevel(Application.loadedLevel);
}
}

Just make rename and edit the Die() function to destroy whatever object goes off screen

Yeah it worked, thamk you guy!! :):slight_smile:

I assume your camera wont rotate much, so the walls will certainly be out of view in several seconds.
So you could use a timeout for the Destroy function.

In case your camera does move and you use Renderer.isVisible to check if you should destroy the objects, that means the player could move avay then back again and see a hole where the wall should be. But this can only happen if your walls are moving slowly.