Raycast Down with Approximation Search

I’ve got an approximation search and would like to ad from the BezierCurve Point the Point on the Ground. => but for correct Result the Point on the Ground must be calculated every Time on the approximation search (due to correct distances)

Approximation Search Code:

float step = 	0.1f;
float t = 		step;
float lastT = 	new float();


float distance = 5;

/* Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t) is a Vector3 Equation for a Point on the Bezier Curve */

while (t >= 0 && t <= 1f)
{

    while (t < 1f && Vector3.Distance(Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t), last_spawn) < distance){
        t += step;}
    step /= 100;
    while (t > lastT && Vector3.Distance(Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t), last_spawn) > distance){
        t -= step;}
    step /= 100;
    if (t > 1f || t < lastT){
        break;}
    if(step < 0.000001f){
        myList.Add(Bezier.GetPoint(Vector3_A,Vector3_B,Vector3_C,Vector3_D,t));
        lastT = t;
        step = 0.1f;
        
    }
}

(Pseudo Code)

Now because the BezierLine is never really aligned with the Surface (Terrain) I need to get the Point on the Ground. If I now Add following Vector3.RaycastDown_Position(); to the Bezier.GetPoint(a,b,c,d,t); Method => Bezier.GetPoint(a,b,c,d,t).RaycastDown_Position();
the Editor will freeze and get’s Laggy!

Raycast Down Code

public static Vector3 RaycastDown_Position(this Vector3 t){
    RaycastHit hit;
    if(Physics.Raycast(t + (Vector3.up * 20),Vector3.down,out hit,Mathf.Infinity)){
        t.y = hit.point.y;
        }
    return t;
}

Question:

What would be a better Approach to avoid Laggy Editor, or even Freezes?

if I add the RaycastDown Method after the approximation search, it’l cause inaccurate Result at the distance between the Calculated Points!
thanks @Bunny83 for any suggestion =)

I did now some research about getting / placing objects on Terrain, with alot of Calls for height!

Raycast Down method

This Method is good to use on single objects, and returns aswell the normal’s for Rotation, align objects on Ground. Performance wise, it’s not recomended for alot of calls like 10000 and more => raycastcommand can be fazter, but still bot recomended.

2D float[ , ] GetHeights Method

Search a 2D array with y and x worldposition for a height. Can be used with the job’s system => but generally slow => just refresh the 2Darray when Terrain has changed, or performance is beyond good and evil.

SampleHeight / Current in use, Best Solution

i use this now, it’s realy fast to get the height on a Vector3 Position, even with 50000 and more calls. just need to be sure that the calls are not every frame, only on change of the bezier or other major changes, which affect the position and the current height