Search Unity

transform.rotation.y = Input.mousePosition.x; not working help!

Discussion in 'Scripting' started by ThatOneCake, Feb 21, 2020.

  1. ThatOneCake

    ThatOneCake

    Joined:
    Dec 2, 2018
    Posts:
    36
    Code (CSharp):
    1.  void Update()
    2.     {
    3.       transform.rotation.y = Input.mousePosition.x;
    4.     }[/code
    5.  
    6. so i got this code wich i dont see anny problems with but it gives me this error
    7.  
    8. Assets\movement.cs(18,7): error CS1612: Cannot modify the return value of 'Transform.rotation' because it is not a variable
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    There are two major problems here:
    1. Transform.rotation is a Quaternion. The x,y,z and w (!) components are not angles. Quaternions are used for performance reasons and to prevent gimbal lock. Whenever possible, work with these values by applying rotations to them, instead of setting a rotation. If you want to set a rotation like you tried above, transform.eulerAngles is what you are looking for. EulerAngles contains the actual rotation on each axis - however it is not free of gimbal lock and should generally only be used as an output to check things with.
    2. The error is caused since you cannot directly set the x,y,z components - neither for rotation nor for eulerAngles. When setting eulerAngles, you need to give it a whole new Vector3. If you dont want to change any values other than the y value, just reuse the old values, ie transform.eulerAngles.x for the x-component of the new vector.
    Edited: Rewrote wrong / easily misunderstandable explanation
     
    Last edited: Feb 21, 2020
  3. ThatOneCake

    ThatOneCake

    Joined:
    Dec 2, 2018
    Posts:
    36