Upper limit for raycasting?

What’s the upper limit for the amount of raycasts Unity can perform without affecting the frame rate?

Here is a script you can use to generate a bunch of raycasts and assess the impact on frame rate. From a quick test it appears my desktop PC (Windows 7, 3.4GHz, 16G RAM) can handle around 300 raycasts per frame with no appreciable impact on frame rate, but at 400 frame rate starts to drop, and at 5000 we’re starting to cripple it. In my tests it didn’t seem to make any difference whether I retrieved the hit info or not.

using UnityEngine;

public class RaycastTest : MonoBehaviour
{
    public bool doRaycasts = false;
    public int numRaycasts = 100;
    public bool getHitInfo = true;
    
    private int numHits = 0;
    private float fps = 0.0f;
    
    void Update()
    {
        // Keep running average of frame rate to smooth out instantaneous jitters.
        float fpsinstant = 1.0f / Time.deltaTime;
        fps = Mathf.Lerp(fps, fpsinstant, Time.deltaTime);
        
        if (doRaycasts)
        {
            numHits = 0;
            for (int n = 0; n < numRaycasts; ++n)
            {
                Ray ray = new Ray(transform.position, Random.onUnitSphere);
                if (getHitInfo)
                {
                    RaycastHit hitInfo;
                    if (Physics.Raycast(ray, out hitInfo))
                    {
                        ++numHits;
                    }
                }
                else
                {
                    if (Physics.Raycast(ray))
                    {
                        ++numHits;
                    }
                }
            }
        }
    }
    
    void OnGUI()
    {
        GUILayout.Label(string.Format("{0} raycasts

{1} hits
{2} fps", numRaycasts, numHits, fps));
}
}

Note that you need to set Vsync Count to Don’t VSync in your Quality settings to get non-locked frame rates. Keep an eye on my frame rate counter, the stats panel, profiler, etc. for different sources of information about performance. And of course performance will vary with the machine or device in use, as well as where the bottlenecks are in your application. I’m not sure if my naive random generation of rays affects the results.

As always with profiling, measure your typical and worst-case usage, don’t rely on data from other people.