- Home /
How to disable gameObjects when they enter a trigger
So as you can see in the photo there is a box collider as a trigger behind the camera. What im trying to do is use the box to cull gameObject behind the camera. When the gameObject such as a building enters the trigger it will disable the gameobject and when the gameObject exits the trigger the object will enable. But i'm not sure how to make this work.
Answer by Spinnernicholas · Sep 30, 2014 at 09:20 PM
Put this on the objects you want to do this to.
void OnTriggerEnter(Collider other) {
renderer.enabled = false;
}
void OnTriggerExit(Collider other) {
renderer.enabled = true;
}
You may need to add code to check if the other is the trigger you want.
This didn't work. I copy and pasted the code so it's exact, and i put the script on the building, and the building has a box collider, but when the trigger hits the collider it does nothing:(
Answer by bubzy · Sep 30, 2014 at 10:25 PM
you can also use this
http://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
I've found it to be quite useful when triggers are being annoying :)
how would i write my script using this example to disable the renderer?
i would put this on the buildings
void checkCollision()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, 1f,11);
int i=0;
while(i < hitColliders.Length) //whiles can be dangerous if you don't make sure that the condition will definitely be met, in this circumstance it is.
{
if(hitColliders[i].tag == "player")//or camera or whatever tag it is.
{
renderer.enabled = false;
i = hitColliders.Length +1;
}
else
{
renderer.enabled = true;
}
i++;
}
}