About mouse wheel control distance

I found one, use the mouse to drag the control of the camera

I like to add mouse wheel to control the distance

I found it only work after the left mouse button is pressed

Please help me

var target : Transform;
var distance = 20.0;
 
var xSpeed = 180.0;
var ySpeed = 90.0;
 
var yMinLimit = 0.0;
var yMaxLimit = 80;
 
var speed : float = 0.14;
 
private var x = 0.0;
private var y = 0.0;
 
 @script AddComponentMenu("Camera-Control/Mouse Orbit")
 
function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;
 
    // Make the rigid body not change rotation
    if (GetComponent.<Rigidbody>())
        GetComponent.<Rigidbody>().freezeRotation = true;
}
 
function Update () {
 
    if (target && Input.GetMouseButton(0)) {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
          
        y = ClampAngle(y, yMinLimit, yMaxLimit);
                 
        var rotation = Quaternion.Euler(y, x, 0);
        var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
         
        transform.rotation = rotation;
        transform.position = position;


        
    }
    
    if (Input.GetAxis("Mouse ScrollWheel")> 0){

        distance = distance + 1;

    }

    if (Input.GetAxis("Mouse ScrollWheel")< 0){

        distance = distance - 1;

    } 


}
 
static function ClampAngle (angle : float, min : float, max : float) {
    if (angle < -360)
        angle += 360;
    if (angle > 360)
        angle -= 360;
    return Mathf.Clamp (angle, min, max);

You just need to rearrange the code order. In the script you posted, you are changing the distance with the mouse wheel. But the distance isn’t applied to the position unless you hold left mouse button. So all you need to do is to take the code where you’re actually setting the position and rotation out of the if statement.

function Update () {
  
     if (target && Input.GetMouseButton(0)) {
         x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
         y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
           
         y = ClampAngle(y, yMinLimit, yMaxLimit);  
     }
     
     if (Input.GetAxis("Mouse ScrollWheel")> 0){
         distance = distance + 1;
     }
 
     if (Input.GetAxis("Mouse ScrollWheel")< 0){
         distance = distance - 1;
     } 

     var rotation = Quaternion.Euler(y, x, 0);
     var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
          
     transform.rotation = rotation;
     transform.position = position;
 }