Version: 2018.3 (switch to 2019.1)
LanguageEnglish
  • C#

Physics.RaycastNonAlloc

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

public static int RaycastNonAlloc(Ray ray, RaycastHit[] results, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

Parameters

rayThe starting point and direction of the ray.
resultsThe buffer to store the hits into.
maxDistanceThe max distance the rayhit is allowed to be from the start of the ray.
layerMaskA Layer mask that is used to selectively ignore colliders when casting a ray.
queryTriggerInteractionSpecifies whether this query should hit Triggers.

Returns

int The amount of hits stored into the results buffer.

Description

Cast a ray through the Scene and store the hits into the buffer.

Like Physics.RaycastAll, but generates no garbage.


public static int RaycastNonAlloc(Vector3 origin, Vector3 direction, RaycastHit[] results, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

Parameters

originThe starting point and direction of the ray.
resultsThe buffer to store the hits into.
directionThe direction of the ray.
maxDistanceThe max distance the rayhit is allowed to be from the start of the ray.
layermaskA Layer mask that is used to selectively ignore colliders when casting a ray.
queryTriggerInteractionSpecifies whether this query should hit Triggers.

Returns

int The amount of hits stored into the results buffer.

Description

Cast a ray through the Scene and store the hits into the buffer.

using UnityEngine;

public class ExampleClass : MonoBehaviour { // The size of the array determines how many raycasts will occur RaycastHit[] m_Results = new RaycastHit[5];

void Update() { // Set the layer mask to all layers var layerMask = ~0;

// Do any of the rays hit? if (Physics.RaycastNonAlloc(transform.position, transform.forward, m_Results, Mathf.Infinity, layerMask) > 0) { foreach (var result in m_Results) { // Check for null since some array spots might be if (result.collider != null) { Debug.Log("Hit " + result.collider.gameObject.name); } } } else { Debug.Log("Did not hit"); } } }

Did you find this page useful? Please give it a rating: