Search Unity

Bug Why does this cause an infinite loop?

Discussion in 'Editor & General Support' started by osciz, Sep 8, 2022.

  1. osciz

    osciz

    Joined:
    Jun 4, 2021
    Posts:
    1
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Camera_Rotation : MonoBehaviour
    6. {
    7.     public float sensitivity = 10.0f;
    8.     public float maxYAngle = 80.0f;
    9.     private Vector2 currentRotation;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.        
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         if (Input.GetMouseButtonDown(1))
    20.         {
    21.             while (Input.GetMouseButtonDown(1))
    22.             {
    23.                 Cursor.lockState = CursorLockMode.Locked;
    24.                 currentRotation.x += Input.GetAxis("Mouse X") * sensitivity;
    25.                 currentRotation.y -= Input.GetAxis("Mouse Y") * sensitivity;
    26.                 currentRotation.x = Mathf.Repeat(currentRotation.x, 360);
    27.                 currentRotation.y = Mathf.Clamp(currentRotation.y, -maxYAngle, maxYAngle);
    28.                 Camera.main.transform.rotation = Quaternion.Euler(currentRotation.y, currentRotation.x, 0);
    29.                 if (Input.GetMouseButtonDown(1) == false)
    30.                 {
    31.                     break;
    32.                 }
    33.             }
    34.         }
    35.         else if (Input.GetMouseButtonDown(1) == false)
    36.         {
    37.                 Cursor.lockState = CursorLockMode.None;
    38.         }
    39.     }
    40. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Unity will lock up 100% of the time EVERY millisecond your scripting code is running.

    Nothing will render, no Debug.Log() will come out, no Input will be processed, no GameObjects or transforms will appear to update.

    Absolutely NOTHING will happen... until your code either:

    - returns from whatever function it is running

    - yields from whatever coroutine it is running

    As long as your code is looping, Unity isn't going to do even a single frame of change. Nothing.

    No exceptions.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,935
    Because an input starts true at the beginning of a frame, and remains true until the end of the frame.

    So once you enter that loop, it's never going to exit it as the current frame is never going to end. Your while loop is unnecessary.