- Home /
Destroying an object after its out of sight !
I have a project which I load two road planes one after another to create endless road.I also have a script attached to camera which creates tree's.All of the code works perfectly fine the tree's are perfectly created but I want to destroy them after they are out of the camera's sight.I tried to destroy them by using destroy(gameobject) but I destroy myself.
So can you help me in this guys ?
My code:
void generateSideTress( )
{
GameObject treeObj = GameObject.Instantiate( sideTres[ Random.Range(0,sideTres.Length-1 ) ] ) as GameObject;
treeObj.transform.position = new Vector3( Random.Range(-80,-60 ) ,0 , playerObj.transform.position.z + 780 ) ;
treeObj.transform.Rotate (0, Random.Range (0, 36) * 10, 0);
}
My code to destroy them I thought that maybe if I destroy them after a second it may work but it doesnt. (not works)
Destroy (treeObj, 1);
Your trees are moving from one place to another? if they are moving then you can set condition on distance and you can destroy it after they go out of camera sight.. Dharmesh
Answer by Andres-Fernandez · Sep 18, 2014 at 11:12 AM
Check function OnBecomeInvisible. You can set it in your trees code with a Destroy call to themselves. Although as @HarshadK suggest, better use pooling.
Answer by Kajal · Sep 18, 2014 at 11:45 AM
Add this code to your Tree Object...
void Update ()
{
Vector3 position=Camera.main.ScreenToWorldPoint(new Vector3(Screen.width,Screen.height,0f));
if(transform.position.x > position.x)
{
Destroy(gameObject);
}
}
Your answer
Follow this Question
Related Questions
destroying game object in a specific transform 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Destroy a Gameobject with a UI Button 3 Answers
The name "Destory" Does not exist in the current context 2 Answers
2D C# destroy a GameObject on collision 2 Answers