- Home /
Finding GameObjects within a radius?
i want to find the gameobjects around my player. what i want to do is find all the gameobjects within a certain area around my player and activate them. i am working on an openworld game. please help.
Answer by fafase · Sep 08, 2013 at 11:12 AM
Do yourself a favor and make it simple, use http://docs.unity3d.com/Documentation/ScriptReference/Physics.OverlapSphere.html
This will return all colliders within radius. From there you can access gameObject.
EDIT:
If the objects are not active you may want to create an array and store all objects at Start, then you can perform:
Transform [] array;
void GetInactiveInRadius(){
foreach (Transform tr in array){
float distanceSqr = (transfor.position - tr.position).sqrMagnitude;
if(distanceSqr < rangeSqr)
tr.gameObject.SetActive(true);
}
}
err one question...it returns all the colliders..ok...well...all the gameobjects in my scene are at first NOT active evertything is set to not active..will it still return colliders?? i hope it does cuz i thot if the object is set to setactive ( false ) the colliders hide with it
i dont understand.. i am new to unity....well...will overlap sphere return colliders of even diabled objects?? becuz my sole purpose is to enable the objects in within a certain area around the player
There could be workaround, first you have objects active, colliders as IsTrigger but all other scripts are inactive and using OverlapSphere, you set them to active.
Other way is using Linq:
float distance;
var transformArray = (GameObject)FindObjectsWOfType(typeof(GameObject))
.Select(go => go.transform)
.Where(t => Vector3.Distance(t.position - transform.position) < distance
.ToArray();
This will return an array of objects within distance. But this is pretty slow and if you do that once in a while, you can get away with it, if you do that in the Update, get ready for some slow motion effect.
Not sure though it works on inactive object.
$$anonymous$$aybe your best solution is an array in which you store them all at the beginning, then inactive the one you want, and later on perform the check:
void GetInactiveInRadius(){
foreach (GameObject obj in array){
if(Vector3.Distance(transfor.position,obj.transform.position) < distance)
obj.SetActive(true);
}
}
Answer by sagivo · Jun 04, 2016 at 03:53 PM
simply use Physics.OverlapSphere Physics.OverlapSphere (someposition, someradius);
Your answer
Follow this Question
Related Questions
Alternatives to GameObject.Find(); 1 Answer
Finding Children question 3 Answers
Find all gameObjects with same tag 1 Answer
Search for specific entity in an array? 1 Answer
Organize around inactive GameObjects not being findable 0 Answers