- Home /
multiple overlapspheres on a single array
I'm trying to add 2 different overlap spheres (one on the right and on on the left) to one array.
I've been using
colliders = Physics.OverlapSphere(transform.position + new Vector3(0, 0, 1), 0.1f);
but is there a way for me to make it
colliders = Physics.OverlapSphere(transform.position + new Vector3(0, 0, 1), 0.1f) + Physics.OverlapSphere(transform.position + new Vector3(0, 0, -1), 0.1f) ;
or like colliders.add
or something?
Answer by andzq · Jun 29, 2021 at 11:27 PM
If I understand that correctly, you want to cast Physics.OverlapSphere twice with different positions and combine the two resulting Collider[] arrays to a single Collider[] array?
---
If so, I can suggest two solutions.
---
Create a third array and fill it with the results of the existing two arrays in a loop:
void OverlapSphereRaycast() { Collider[] first = Physics.OverlapSphere(transform.position + new Vector3(0, 0, 1), 0.1f); Collider[] second = Physics.OverlapSphere(transform.position + new Vector3(0, 0, -1), 0.1f); Collider[] all = new Collider[first.Length + second.Length]; for (int i = 0; i < first.Length; i++) { all[i] = first[i]; } for (int i = 0; i < second.Length; i++) { all[i + first.Length] = second[i]; } }
Use System.Linq and it's function "Concat" to combine two arrays
void OverlapSphereRaycast() { Collider[] first = Physics.OverlapSphere(transform.position + new Vector3(0, 0, 1), 0.1f); Collider[] second = Physics.OverlapSphere(transform.position + new Vector3(0, 0, -1), 0.1f); Collider[] all = first.Concat(second).ToArray(); }
or:
void OverlapSphereRaycast()
{
Collider[] all = Physics.OverlapSphere(transform.position + new Vector3(0, 0, 1), 0.1f)
.Concat(Physics.OverlapSphere(transform.position + new Vector3(0, 0, -1), 0.1f))
.ToArray();
}
//Edit: In order to use Linq you'll need to write "using System.Linq;" at the top of your script
Your answer

Follow this Question
Related Questions
Confused using Arrays 1 Answer
Trying to use "OverlapSphere" to detect closest enemy 1 Answer
How to get the nearest collider, or just a single collider from Physics.OverlapSphere? 1 Answer
Destroy objects within ordered Array by line of sight 1 Answer
How to get an array of transforms and move GameObject for certain duration to that transforms list 0 Answers