How to fade many objects towards camera


I want to be able to fade objects that the camera is moving towards. However, I need to be able to click/drag on the Player at all times.

I am aware that as a condition I can use something like;

if(Vector3.Distance(transform.position, Camera.main.transform.position) > fadeDistance)
//fade out

which is attached to the object to be faded. However, if there are many objects I would prefer to have a script attached to the camera (or an object on the camera).

So with this in mind, I wanted to know how to store/check the objects moving towards the camera and then fade them. The camera is static in the X-Y plane and just moving along the Z.


If the objects have colliders you can use Physics.OverlapSphere centered on the camera to return the colliders of all objects within a given radius.

Alternatively, you can tag all objects that you want to fade out with a specific tag, and then call GameObject.FindGameObjectsWithTag, although I would caution against doing this every single frame. Do it once when the scene is initialised (or if the state of the objects changes) and then store the array for later checks.

Given your camera only moves in one axis, you could also optimise your distance check by just comparing z-values, rather than the 3-dimensional distance, which involves calculating square roots and can impact performance depending on how many checks you are doing.