- Home /
Enabling and Disabling gameobjects
So I've probably spent the previous hour trying to work through this code, to the point where I've merely copied and pasted it and it still doesn't work... what is wrong with this? I am trying to only enable gameobjects which are a certain radius away from me. This code somewhat works as I will spawn in an some objects will have loaded, and some have not; however the ground directly below the player is also being disabled.
Collider[] c = Physics.OverlapSphere(this.gameObject.transform.position, 10);
foreach(Collider co in c)
{
if(Vector3.Distance(this.gameObject.transform.position, co.gameObject.transform.position) > 2)
{
gameObject.SetActive(false);
}
if(Vector3.Distance(this.gameObject.transform.position, co.gameObject.transform.position) < 2)
{
gameObject.SetActive(true);
}
}
I don't think your objects will ever get reenabled again as the the OverlapSphere() won't return disabled colliders (e.g. colliders in a disabled gameobject).
You could probably just disable the mesh renderer component ins$$anonymous$$d.
In addition your floor does not get reenabled in any case as you are computing the distance using the objects origin. If your floor is one giant plane or something like that, the origin most usually is further away than 2 units most of the time.
Answer by Landern · Aug 09, 2016 at 02:54 PM
You may want to start using Layers and the Layer parameter of Physics.OverlapSphere to exclude objects from being picked up. Your SetActive code doesn't currently care what the object is so long as it has a collider that was returned from Physics.OverlapShere, thus the ground being disabled, including a specific layer will wrap this up for you.