Is Physics.RaycastNonAlloc() better than Physics.RaycastAll()?

        private bool InteractWithComponent()
        {
            RaycastHit[] raycastHits = new RaycastHit[3];
            int size = Physics.RaycastNonAlloc(GetMouseRay(), raycastHits);
            for (int i = 0; i < size; i++)
            {
                IRaycastable[] raycastables = raycastHits[i].transform.GetComponents<IRaycastable>();
                foreach (IRaycastable raycastable in raycastables)
                {
                    if (raycastable.HandlerRayCast(this))
                    {
                        SetCursor(raycastable.GetCursorType());
                        return true;
                    }
                }
            }
            return false;
        }

"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.

The raycast query ends when there are no more hits and/or the results buffer is full. The order of the results is undefined. When a full buffer is returned it is not guaranteed that the results are the closest hits and the length of the buffer is returned. If a null buffer is passed in, no results are returned and no errors or exceptions are thrown."

I don’t know what it means. If I need ordered array. Do I need to set the “raycastHits” shorter length? For example size is 2 or 3.

No, you can’t get an ordered array out of it. If you set the size of the array to 2, the ray will continue until it has filled the buffer (i.e. found 2 hits) or there is nothing more to hit. The best way to have the hits ordered is to sort them once you have them (I think Sam will still get to that).

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms