In my top scrolling space shooter I'm giving every enemy some sort of script intelligence, but I obviously only want this AI to kick in when they are within view of the camera. Now it is possible to add a timer variable which counts down and then manually alter it to match the rate at which the camera will reach the enemy, but that feels very inefficient. Is there a good way to get a boolean that turns true as soon as the camera sees the object?
You're looking for Renderer.isVisible
What you'd probably do is: In every update (or every few updates, could be also controlled via a Coroutine), check whether the state of renderer.isVisible has changed (went from false to true, or vice versa). When the object became visible, start your AI.
Or, you could have your AI code in the if:
Depends much on how your AI is exactly implemented.
There's one thing to be aware of, though: isVisible will also be true if the shadow of the object is visible (which sometimes is the case even though you wouldn't expect it). So watch out with this, if you're using shadows.
Oh, and of course: any camera (including scene view cameras in the editor). So that also requires be a little careful when testing this.
answered Sep 17 '10 at 09:52 AM
Other good answers to this question can be found here. In particular, if you have multiple cameras you can use OnWillRenderObject instead.
Another way not mentioned is to use raycasting. That would be the way to go if you want to account for obstacles blocking the view of the camera/enemy. Here is an answer on that topic.
answered Sep 17 '10 at 10:54 AM