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

I’m trying to make a cube look at the player:

        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

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.

2 Likes

Translation

Quaterion tempRotation = transform.rotation;
tempRotation.eulerAngles = new Vector3(0,0,0);
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.

1 Like

Great. Thanks for the help.