- Home /
How to count the number of clones within view?
Hello!
I have a random ghost generate when triggered, using Instantiate. They appear for a few seconds before destroying themselves. While they're active, the player has to try and take a picture with as many of them on the screen at once as possible.
Everything in my code is working fine up until this point, and I'm just trying to figure out how to make a variable count the number of ghosts within the view of the camera. I looked at a few other similar questions, and a loop with "isVisible" counting the renderers is working, but the problem it counts each piece of the rendered items, which isn't good for my ghosts which have multiple parts.
It also counts ALL renderers, not just those on the ghosts.
How would I count the number of ghosts (clones from Instantiate) that are on the screen?
Here's my code for the counter:
if(Input.GetMouseButtonDown(2) && RaisedCamera == true){
Renderer[] renderers = (Renderer[])(FindObjectsOfType(typeof(Renderer)));
Count = 0;
foreach(Renderer i in renderers) {
if(i.isVisible) {
Count += 1F;
}
}
it's possible you will have to carefully keep track of the ghosts in a pool
http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html
then, just count them in that pool !
Answer by aldonaletto · Oct 29, 2012 at 11:19 AM
You could use some specific tag for the ghosts (like Ghost, for instance), grab them all in an array and check their isVisible properties:
if(Input.GetMouseButtonDown(2) && RaisedCamera == true){
GameObject[] ghosts = GameObject.FindGameObjectsWithTag("Ghost");
Count = 0;
foreach(GameObject ghost in ghosts) {
if (ghost.renderer.isVisible) {
Count++;
}
}
...
But be aware that isVisible simply shows whether the object's bounding volume is inside or touching the view frustum of any camera. If a ghost is out of view but its bounding box touches the view frustum, isVisible returns true. The same applies for a ghost hidden by a wall, or visible in a second camera (if any).
Your answer
![](https://koobas.hobune.stream/wayback/20220613083024im_/https://answers.unity.com/themes/thub/images/avi.jpg)