I tried for 2 days to solve my problem and finally gave up on trying this on my own.
Here’s what i want my script to do:
Find Objects with a certain tag, within a certain range (working)
Find the “nearest” of those objects (working)
Set the shader color to yellow for closest object within range (kinda working)
Set the shader color to green for everything else (kinda working)
The Problem:
When my object was, but is no longer in range, i can’t figure out, how to change it’s color back to green.
When no object should be in range anymore, the “last-to-be-closest”-object stays yellow.
Also, if an object goes out of range, set it to green
It sounds to me like you can make things much easier if you instead look at it like this:
Find ALL objects, REGARDLESS of range
Set the closest one to yellow
Set the rest to green
If for some reason you can’t do that, then I recommend you store the closest one in a variable when you change its color to yellow, and then the next time your code runs it should change the object in that variable to green before overwriting it with the new closest.
If i use Mathf.Infinity for the Range it does check everything yeah, but i need to define a range somewhere for when it is out-of-range - and if nothing is in range, set everything back to green (even if it was yellow / in range before).
And that’s the part i can’t wrap my head around right now.
Set each object to green, while checking distance and keeping track of which object is the closest
If the closest object is within range, set it to yellow
This would result in you setting the color of the closest object twice, but you’d only need to loop through the list of objects once and it would be pretty straight forward to implement.