0
\$\begingroup\$

I made an infinite path using prefab.Path moving in the negative x direction. I want to destroy the path clone once it goes offscreen.

My path move script is:

var Speed:float = 5;
var hasseen:boolean;
function Start () {
    rigidbody2D.velocity.x = -1 * Speed;
    hasseen=false;
}
function Update() {
    if(renderer.isVisible) {
        hasseen=true;
    }
    if(hasseen) {
        if(!renderer.isVisible) {
            Destroy(gameObject);
        }
    }
}

and my prefab script is this:

var path_pre:Transform;
var i:long = 0;
function Update() {
    if(i<1000000) {
        Instantiate(path_pre, Vector3(i*25, -3, 0), Quaternion.identity);
        i++;
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Rather than polling isVisible many people use OnBecameInvisible()/OnBecameVisible(). Note however that they will report the object as visible if while it is drawn by any camera i.e. the Scene window counts. As a result the game can behave differently in editor. \$\endgroup\$ – Kelly Thomas Mar 9 '15 at 12:28
0
\$\begingroup\$

Create a game object with a box-collider which exactly covers your screen. Make the collider a trigger and attach a script to the object which implements the OnTriggerExit method. The documentation article for OnTriggerExit has an example which covers exactly this use-case:

function OnTriggerExit(other) {
    // Destroy everything that leaves the trigger
    Destroy(other.gameObject);
}

This example destroys all game objects which leave the screen. When you want to limit this only to specific objects, make it check the other's name, tag or check if it has a specific component to identify it as an object it is supposed to destroy.

\$\endgroup\$
  • \$\begingroup\$ i thought destroying path clone will save my RAM which will maintains the games speed,but game starts lagging after 3-4 mins very poorly...what is the reason for this? \$\endgroup\$ – Rajat Sharma Mar 9 '15 at 16:13
  • \$\begingroup\$ @RajatSharma There are about a million possible reasons for this. \$\endgroup\$ – Philipp Mar 9 '15 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.