Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Error in my Lock Rotation C# Script. Help Please.

Discussion in 'Scripting' started by Vulshok, Jun 11, 2014.

  1. Vulshok

    Vulshok

    Joined:
    Jun 11, 2014
    Posts:
    1
    Error: Cannot modify a value of UnityEngine.transform.rotation. Consider storing the value in a different variable

    I am new to scripting, if someone could help me and give me an explanation why this is happening . I would greatly appreciate it. Thanks

    Code (CSharp):
    1.         //Lock MouseXandY rotation
    2.  
    3.         transform.rotation.eulerAngles = new Vector3(
    4.             Mathf.Clamp(transform.rotation.eulerAngles.x,minimumX,maximumX),
    5.             Mathf.Clamp(transform.rotation.eulerAngles.y,minimumY,maximumY),
    6.             Mathf.Clamp(transform.rotation.eulerAngles.z,0,0));
    7.     }
    8. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    well it's telling you...

    store the current rotation in a variable, work with that variable, apply that variable back to transform.rotation


    edit: it's also not quite that simple, if you google "unity clamp rotation" you'll find quite a few posts on this (it's a common sticking point by the looks of it)
     
    Vulshok likes this.
  3. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Quaternion's are structs. This means, when you get transform.rotation, what you get is a copy of the Quaternion, but not the actual rotation Quaternion itself. Changing the .eulerValues of a rotation's copy will not apply to the original transform like you expect.

    This is why we need to make another Quaternion, put the new values in our fresh Quaternion, then send the entire struct back to transform all at once.

    Code (csharp):
    1. // Get a copy
    2. Quaternion updatedQuaternion = transform.rotation;
    3. // Modify the copy's eulerAngles
    4. updatedQuaternion.eulerAngles = new Vector3(..., ..., ...);
    5. // Overwrite the existing transform.rotation
    6. transform.rotation = updatedQuaternion;
     
  4. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    I know this is from the fact that the ORDER of rotations matter, so rotating x first then y is different than rotating y first then x. I'm not sure what the original poster is attempting to do, but it sounds like something I've heard animators talk about, Gimbal Lock.
    https://www.google.com/search?q=gimbal lock animation