- Home /
How to destroy an object - destroy problems
Hi, i'd like to make a game object falling from the top to the bottom of the screen. I want to destroy it when its below the bottom and its not visible. How do i destroy it. In the update method of the class attached to that gameobject i do: void Update () { if (GetComponent().isVisible ) { transform.Translate(0, 2f * Time.deltaTime, 0);
}
else
{
Destroy(gameObject);
}
}
If i put the destroy, the object does not even appear when i start the game. If i remove the destory, the object appears and starts falling, but does not get destroyed when not visible. HELP! <3
Is it visible when you start the game?
And please can you format your code properly in the question? The GetComponent() call is confusing as it stands (because there doesn't appear to be a type supplied).
Answer by JedBeryll · Oct 02, 2016 at 11:53 AM
How about this method? https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnBecameInvisible.html
Answer by Dream_in_code · Oct 02, 2016 at 02:45 PM
You can create a box collider under your screen and tag it as "deathLine". After gameobject falls it will touch the collider. The idea is to destroy the gameobject when it touches the collider. So inside your gameobject add a few line of codes :
void OnTriggerEnter2D(collider2d other)
{
if(other.tag == "deathLine")
{
destroy(gameobject)
}
}
Answer by stratos_kakalis · Oct 02, 2016 at 03:53 PM
If you just want the gameobject to be invisible and dont care if it keeps going when its off screen you can turn off the mesh renderer and turn it back on when restarting your game. If you want to pause it's movement as well you'll have to do it on your own or you can share your code and I will help you, although it should be fairly simple :).