- Home /
physics.OverlapSphere and loops troubles
Hi! having some troubles with my loops. So this is what im doing and need to do. Im moving an object with transform. I have to do it this way for technical reasons. Now, i have to have some collision detection on this object, yea i know, transform.position and collisions is not the way to go but i have to do it this way so im OverlapSphere to check collision. I have to be able to detect if my object is hitting something from all points around it so a normal RayCast wont do.
It's like a selecting feature or, when you mouse over and objects in some game, they light up, but this is in 3d space and i use game objects to do it.
Now here is the part where im having trouble getting it to work the way i want it to.
When my object is colliding with another object in the world i want the moving object to turn of it's renderer and the object i hit, i want to change the material on. now, i got this to work, half way. i can turn of my moving objects renderer and change the material on the other object. But when i move away from object i hit, i want the moving objects renderer to turn on and the material of the hit object to go back to normal. I cant get this last part to work.
i've tried
Collider[ ] hitColliders = Physics.OverlapSphere(transform.position, radius);
foreach(Collider hit in hitColliders){
//check if im hitting an object that i want to light up
if(hit.tag == "interactive"){
renderer.enable = false;
}
//if im not hitting anything
if(hit.tag == null){
renderer.enable = true;
}
}
the problem i guess is it only does loops while im hitting an object, so it knows im hitting something, but as soon the two objects colliders isnt overlapping anymore, it stopps doing anything...I've tried alot of different ways of writing it but im stuck`enter code here`
So, not a problem with OverlapSphere. Really a commonish program$$anonymous$$g "no auto reset" problem.
The trick is to remember the objects that were hit, and specifically check if they are now out of the area. Could spawn a coroutine for each, that checks every frame. Or could put them on a list that you check every frame. A shortcut, for "am I out of range yet?" would be to just check distance to the object.
Or, poor mans's hack: before doing the overlap check, reset everything's color.
Your answer
![](https://koobas.hobune.stream/wayback/20220613141939im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Infinite Looping Crash 2 Answers
Pre-Determined Path for Helicopter 1 Answer
For loop not working 1 Answer
iTween - How to move an object that is currently undergoing a "tweening"? 1 Answer