Search Unity

Cannot modify a value type return value of `UnityEngine.Transform.rotation'

Discussion in 'Scripting' started by 2close4missiles, Mar 30, 2015.

  1. 2close4missiles

    2close4missiles

    Joined:
    Feb 13, 2015
    Posts:
    13
    I'm trying to make a cube look at the player:
    Code (CSharp):
    1.         transform.rotation.y = Mathf.Lerp(transform.rotation.y, targetLook.y, smoothLook * Time.deltaTime);
    This is the error I'm getting:
    CS1612: Cannot modify a value type return value of `UnityEngine.Transform.rotation'. Consider storing the value in a temporary variable

    Can anyone tell me why this is happening? I've been having this issue with several other rotation-changing functions as well. Please and thanks.

    PS: I cant use transform.LookAt in this situation
     
  2. Deleted User

    Deleted User

    Guest

    The warning message is exactly telling you what to do, so fixing it schould be simple. As to Why.
    Rotation is of type Quaternion and a Quaternion is a value type (struct) and not a reference type (class).
    Value types are returned by copy. So when you say "Hey whats your rotation" than you are getting a copy of the object and not the actual object back. Modifieing a copy is more or less useless except when you assign the copy back to the rotation.
     
    2close4missiles and Kiwasi like this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Translation

    Code (CSharp):
    1. Quaterion tempRotation = transform.rotation;
    2. tempRotation.eulerAngles = new Vector3(0,0,0);
    3. transform.rotation = tempRotation;
    Don't set xyzw of a quarterion directly unless you know what you are doing. For clarification you do not know what you are doing.
     
    KelsoMRK likes this.
  4. 2close4missiles

    2close4missiles

    Joined:
    Feb 13, 2015
    Posts:
    13
    Great. Thanks for the help.