Home > Software engineering >  Error when trying to change the player's orientation
Error when trying to change the player's orientation

Time:10-05

public class PlayerMove : MonoBehaviour
{
    private float mainCameraRotateY;

    void Update()
    {
        mainCameraRotateY = Camera.main.transform.localEulerAngles.y;

        if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
        {
            Debug.Log(this.transform.eulerAngles.y);
            Debug.Log(mainCameraRotateY);
            this.transform.eulerAngles.y = mainCameraRotateY;
        }
    }
}

The above is a script attached to the player to make the player turn to the direction the camera is looking at when moving.

But an error was reported with this.transform.eulerAngles.y = mainCameraRotateY;

error CS1612: Cannot modify the return value of 'Transform.eulerAngles' because it is not a variable

All other parts can operate normally.

How can i fix this?

CodePudding user response:

var eulerAngles = this.transform.eulerAngles;
eulerAngles.y = mainCameraRotateY;
this.transform.eulerAngles = eulerAngles;

You can't change this.transform.eulerAngles directly because it is internally implemented as a property, not a variable. Because the internal Unity code likely implements a custom setter function, the whole object needs to be assigned at once and individual sub-variables or sub-properties cannot be changed.

CodePudding user response:

Transform.eulerAngles is a property which either returns or takes a complete Vector3 which is a struct and thereby a value type.

This means even if it would compile, it would have no effect since you would only be changing the y component of a returned vector and then immediately throw it away.

In order to change the Transform.eulerAngles you have to actually assign a complete Vector3 to it.

If you want to change a single component of it you have to do it like e.g.

var eulerAngles = transform.eulerAngles;
eulerAngles.y = mainCameraRotateY;
transform.eulerAngles = eulerAngles;
  • Related