I am trying to determine if a prefab is out of camera view so I can destroy it. However the prefab itself doesn't appear to have a render object because renderer.isVisible causes errors. So I tried this, but myRenderer.isVisible is always returning true no matter what.
The prefab is named Bat, and the model inside the prefab is also named Bat. I don't even know if GameObject.Find searches only the current hierarchy or the entire scene. The docs don't say.
function Start()
{
var obj:GameObject = GameObject.Find("Bat");
myRenderer = obj.renderer;
bornTime = Time.time;
}
function Update ()
{
// Randomly change direction.
transform.Rotate(Random.Range(-15,16),Random.Range(-5,6),0);
// Fly forward.
transform.Translate(0,0,speed);
// If I've been alive for more than 5 seconds and I'm off the screen, delete me since I could possibly never return to view.
if (Time.time - bornTime > 5 && myRenderer.isVisible == false)
{
Destroy(gameObject);
}
}
Is this script attached to a Bat? If so, don't find at all. Just use 'renderer.isVisible' and it will tell you if 'this' prefab instance is visible.
If this script is attached to some other object, then Find will return the first Bat it finds. Yes, I'm pretty sure it checks the whole scene. If your Bat is at the top level, you could use /Bat to have it just check the top level. What I've done, to check the 'current' hiearchy (this object and it's children) is something like GameObject.Find (name+"/Bat");
In the script you've posted, I don't see a problem with your usage of isVisible.
Find searches the whole scene. Based on the Update comments, presumably this script goes in the Bat, in which case don't bother with Find.
Note that the 'renderer' getter will only look for a renderer in the same object, so if there is a renderer in a child of the object, that will not find it. Instead you could use:
Besides using GetComponentInChildren to get the correct renderer, make sure that the scene (editor) camera isn't pointing at the object you're checking visibility for.
The editor's camera counts towards returning true for isVisible, very easy to slip up with it