[Unity]Change the color of the nearest object


Hello (…) I’m sorry it’s been a while since I’ve updated.
It has been a long time since I have updated this page due to various reasons.

This time, I would like to describe a method to change the material color of the nearest object based on the attached object in the script.

First, place the objects as desired.

Since this script is set to the main camera, the cube-shaped object is closest to the main camera, so it is OK if the color of this cube-shaped object is changed.

Add an arbitrary tag to the object to be compared for distance as follows. In this case, we set “Target”.

Below is the content of the script placed on the main camera.
The distance between each object with a Target tag and the main camera is compared in a loop.

The object with the smallest return value of the distance function remains until the end, so after the loop, the material color of that object is changed to blue.

The following is the result of the execution.

There may be other efficient methods, but we hope you will find them useful. m(…m