OverlapSphereNonAlloc(Vector3, float, Collider[], int, QueryTriggerInteraction)
Computes and stores colliders touching or inside the sphere into the provided buffer.
Read time 1 minuteLast updated 6 days ago
Definition
- Type: Method
- Namespace: UnityEngine
- Assembly: UnityEngine.PhysicsModule
public static int OverlapSphereNonAlloc(Vector3 position, float radius, Collider[] results, int layerMask, QueryTriggerInteraction queryTriggerInteraction)
Parameters
Center of the sphere.
Radius of the sphere.
The buffer to store the results into.
A Layer mask defines which layers of colliders to include in the query.
Specifies whether this query should hit Triggers.
Returns
Type | Description |
|---|---|
| int | Returns the amount of colliders stored into the |
Remarks
Does not attempt to grow the buffer if it runs out of space. The length of the buffer is returned when the buffer is full. Like Physics.OverlapSphere, but generates no garbage. Additional Resources: Physics.AllLayers.
using UnityEngine;public class ExampleClass : MonoBehaviour{ // Declare hitColliders as a reusable field. private Collider[] hitColliders; // Set the maximum number of colliders that can be detected at once. private const int maxColliders = 10; void Awake() { // Initialize the array just once. hitColliders = new Collider[maxColliders]; } void ExplosionDamage(Vector3 center, float radius) { // Reuse the pre-allocated array for Physics.OverlapSphereNonAlloc. int numColliders = Physics.OverlapSphereNonAlloc(center, radius, hitColliders); // Iterate through detected colliders and send the AddDamage message. for (int i = 0; i < numColliders; i++) { hitColliders[i].SendMessage("AddDamage"); } }}
Additional Resources: Ray cast with layers section of Use of layers in Unity.