How to make a slider follow the mouse?

I’m trying to make a slider so I wrote a script to adjust my slider bar. The problem is that the slider either moves too slow and the mouse outruns it, or moves too fast and the slider out runs the mouse. The code I’m using is below (I’m using Z because the slider moves on the Z axis as the mouse moves along the X axis on the screen).

private var canSlide;
private var lastZ;

private var maxZ : float = 18.03127;
private var minZ : float = 3.302428;

function Start()
{
	canSlide = false;
}

function Update () 
{

	if(canSlide)
	{
		TrySlide();
	}else
	{
		if(Input.GetMouseButtonDown(0))
		{
			var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			var hit : RaycastHit;
			if(Physics.Raycast(ray.origin, ray.direction, hit))
			{
				if(hit.collider.gameObject.name.Equals("VolumeSlider"))
				{
					canSlide = true;
					lastZ = Input.mousePosition.x;
				}
			}
		}
	}
	
	//if mouse button released
	if(!Input.GetMouseButton(0))
	{
		canSlide = false;
	}
	
	lastZ = Input.mousePosition.x;
}

function TrySlide()
{
	var zDiff : float = (lastZ - Input.mousePosition.x) * Time.deltaTime;
	
	gameObject.transform.position.z -= zDiff;
	
	if(gameObject.transform.position.z > maxZ)
	{
		gameObject.transform.position.z = maxZ;
	}else
	{
		if(gameObject.transform.position.z < minZ)
		{
			gameObject.transform.position.z = minZ;
		}
	}
}

The problem is finding the right factor to multiply zDiff by. Is there some formula to figure out the factor?

You could use GUILayout.HorizontalSlider (Input.mousePosition.x,0,Screen.width) to make it follow the mouse horizontally.
or you could use GUILayout.VerticalSlider (Input.mousePosition.y,0,Screen.height) to make it follow the mouse vertically.