Raycast problem

I have to moving objects with different speeds, one object has to follow another. When distance become too small, I need to decelerate following object to normal distance. In my case, Raycast work just once, but I want it work unitl it hits target and then resrt it.

private void holdDisance()
{
    Ray ray = new Ray(transform.position + new Vector3(mindistance, 0, 0), transform.forward);

    Debug.DrawRay(transform.position, transform.forward, Color.red);

    RaycastHit hit;

    if (Physics.Raycast(ray, out hit))
    {

        if (!hitFlag)
        {

            hitFlag = true;
            speed -= deceleration;
            Debug.Log("AAAA");
        }

    }
}

Try using the Vector3.Distance function. You’re conditional would look something like this:

float dist = Vector3.Distance(other.position, transform.position);
if (!hitFlag && dist < 10f)
{
...
}