how to smooth value?

So i need a value to be smoothed over time (not increased at same rate) it focuses the camera to a object instantly, but i want it to be gradually lets say like in 0.5 seconds. here is the script.

    public DepthOfField dof;

    private void Start()
    {
        InvokeRepeating("RefocusUpdate", 0, 0.1f);
    }

    void RefocusUpdate()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            dof.focalLength = hit.distance; // need this to be changed gradually over time (500miliseconds)
        }
    }

Thanks!

Hey there,

perhaps something like this might work for you:

public DepthOfField dof;
    private float convergeFocusTo;
	private void Start()
	{
            convergeFocusTo = dof.focalLength;
		InvokeRepeating("RefocusUpdate", 0, 0.1f);
	}
	
	void RefocusUpdate()
	{
		RaycastHit hit;
		if (Physics.Raycast(transform.position, transform.forward, out hit))
		{
			convergeFocusTo = hit.distance; // need this to be changed gradually over time (500miliseconds)
		}
	} 
	
	public void FixedUpdate()
	{
		dof.focalLength = Mathf.Lerp(dof.focalLength,convergeFocusTo,0.2f);
	}

As NoDumbQuestion said, use interpolation, for example Mathf.Lerp(), but to do it correctly over a given amount of time, you also need to restart the transition of the focalLength whenever a new object is hit. You could do it like this:

[SerializeField] private float transitionDuration = 0.5f; // 500 ms duration, changeable from Editor

private GameObject focusObject;

private float startFocalLength;
private float t;

private void Start () {
    InvokeRepeating("RefocusUpdate", 0, 0.1f);
}

void RefocusUpdate () {
    RaycastHit hit;
    if (Physics.Raycast(transform.position, transform.forward, out hit)) {
        if (focusObject != hit.collider.gameObject) {
            focusObject = hit.collider.gameObject;
            startFocalLength = dof.focalLength;
            t = 0;
        }
        t += Time.deltaTime;
        dof.focalLength = Mathf.Lerp(startFocalLength, hit.distance, t / transitionDuration);
    }
}

Note: this is syntactically correct, but untested code. With this the camera will continue to focus on the object as long as it is being hit, even if it moves closer or farther while refocusing, which will affect the speed of change (can become jittery). You might also want to consider using Mathfx.Sinerp() instead of Lerp(), because it will give a nicer, eased-in transition.