Search Unity

Resolved Quaternion returning wrong value.

Discussion in 'Scripting' started by Snakebearer, May 27, 2022.

  1. Snakebearer

    Snakebearer

    Joined:
    Feb 9, 2013
    Posts:
    26
    First time posting here asking for help. The thing is, I already resolved my issue by using another code.
    But here is the new issue, I don't understand why my code didn't work - and it'll be an issue later on if I'm missusing this as is.

    Scenario:
    I'm making a little minigame. Several rotating cylinders with an opening in them. Every cylinder moves in a different direction, and at different speeds. I'm very happy. But then I realize my code for making their starting rotation randomized doesn't work...
    This is what I had:
    Code (csharp):
    1.  
    2.     [SerializeField] private Quaternion initialRotation;
    3.     [SerializeField] private Quaternion randomStartPos;
    4.     [SerializeField] private bool spinningRight;
    5.     [SerializeField] private int spinningDir;
    6.     [SerializeField] private float spinningSpeed;
    7.    
    8. private void Start()
    9.     {
    10.        //Setting and saving a random Quaternion
    11.         randomStartPos = Random.rotation;
    12.        
    13.        //logic to handle if it's going left or right, and at what speed.
    14.  
    15.         spinningRight = (Random.value > 0.5f);
    16.         if(!spinningRight)
    17.         {
    18.             spinningDir = -1;
    19.         }
    20.         else
    21.         {
    22.             spinningDir = 1;
    23.         }
    24.  
    25.         spinningSpeed = spinningDir * Random.Range(0.3f, 1.0f);
    26.        
    27.         //This is where the issue is. It won't let me use the information from the quaternion. It just sets Z to 1.
    28.  
    29.         transform.rotation = new Quaternion(0,0,randomStartPos.z,0);
    30.  
    31.         initialRotation = transform.rotation;
    32.     }
    33.  
    34.    
    35.  
    36.     private void Update()
    37.     {
    38.         if(isSpinning)
    39.         Spin();
    40.  
    41.  
    42.     }
    43.  
    44.     private void Spin()
    45.     {
    46.         {
    47.           transform.Rotate(new Vector3(0f, 0f, spinningSpeed));
    48.         }
    49.     }
    50.  
    I ended up using:
    Code (csharp):
    1.  
    2. transform.rotation = Quaternion.Euler(0,0,Random.Range(0,360));
    3.  
    Mainly posting it for anyone who googles this specific thing. But for myself, I'm asking this because I wanna know what I did wrong.

    Thank you. :)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Snakebearer and _TheFuture_ like this.
  3. Snakebearer

    Snakebearer

    Joined:
    Feb 9, 2013
    Posts:
    26
    Thanks! This answered exactly what I needed.
    Now I don't have to worry about making that mistake, and I know why! :)