I'm trying to destroy an object when it's out of the camera's view.
My code works correctly on every object in the scene, but when I'm creating an object from a prefab using Instantiate()
, it doesn't works!
Here's Sv_Generator.cs
public class Sv_Generator : MonoBehaviour {
public GameObject generator_proxy;
public GameObject object_prefab;
void Update () {
GameObject new_object = (GameObject)Instantiate(object_prefab, generator_proxy.transform.position, generator_proxy.transform.rotation);
new_object.name = (System.Guid.NewGuid().ToString("N")).Substring(0, 6);
}
}
Here's AutoDestroy.cs, which is attached to the prefab object_prefab
public class AutoDestroy : MonoBehaviour {
void OnBecameInvisible()
{
Destroy(gameObject);
Debug.Log(name + " is out!"); // This line prints!
}
void Update()
{
/// If I put Destroy(gameObject); here, it works!
}
}
Now I start the game. When new objects go off-screen, Debug.Log(name + " is out!");
fires and works as expected, but Destroy(gameObject);
does not fire and nothing happens!
But if I put Destroy(gameObject);
in void Update ()
it works :\
I also tried :
GameObject get_obj = GameObject.Find(name);
Destroy(get_obj);
No luck! :(
How can I make it work ?
Destroy
didn't work:Destroy
is not an immediate function and the object isn't actually removed until the end of frame. \$\endgroup\$