Physics.OverlapSphereNonAlloc
时间: 2024-05-10 17:21:02 浏览: 5
Physics.OverlapSphereNonAlloc is a method in Unity's physics engine that performs a sphere cast and returns an array of all colliders that intersect with the sphere. This method is similar to the Physics.OverlapSphere method, but instead of returning a new array each time it is called, it uses a pre-allocated array to store the results. This can improve performance by reducing garbage collection.
The method takes four parameters: the center of the sphere, the radius of the sphere, an array to store the results, and a layer mask to filter which colliders are included in the results. The method returns the number of colliders that intersect with the sphere.
Here is an example of using Physics.OverlapSphereNonAlloc to get all colliders within a certain distance of a game object:
```
Collider[] results = new Collider[10];
int numColliders = Physics.OverlapSphereNonAlloc(transform.position, 5f, results, LayerMask.GetMask("Enemies"));
for (int i = 0; i < numColliders; i++) {
// do something with the colliders that were found
}
```
In this example, we are using a pre-allocated array of length 10 to store the results of the sphere cast. We are only interested in colliders on the "Enemies" layer, so we pass that layer mask to the method. We then loop through the results array up to the number of colliders that were found and do something with each collider.