- Home /
use Physics.OverlapSphere to detect neighbour of same tag in list of gameObjects
Hello, i have a 10x10 grid of gameobjects stored in a list. The computer will randomly select one of these gameobjects with a raycast. I want to check if this gameobject has any neighbours with the same tag if it is being selected. By using Physics.OverlapSphere i can raycast a sphere around this gameObject and return an array of colliders. I want to remove elements in this array if it doesnt have the same tag as the original object and keep the one that has the same tag. Additionally i want to take these found colliders and assign them as gameobjects and place them in a new array to keep track on all the neighbours with their own tags. How should i go about doing this?
Answer by MakakWasTaken · Sep 26, 2015 at 07:27 PM
You could do something like this:
//Remember:
using System.Collections.Generic //For List class
public float neighbourRadius;
GameObject[] GetNeighbours(Vector3 gobj, string originalTag) {
List<GameObject> newList;
foreach (Collider col in Physics.OverlapSphere(gobj.transform.position, neighbourRadius) {
if (col.tag == originalTag) {
newList.Add(col.gameObject);
}
}
return newList.ToArray();
}