How to rotate a child object only on Y axis without controlling other axis?

I have a 2D platformer player controller that detects whether it’s facing left or right. If it’s facing left, the object it’s holding should rotate 180 degrees on the Y axis.

I’ve tried the below code but it seems to be locking up the X and Z axis as well, preventing the held object from rotating with its parent (the player’s hand).

How can I get it to only flip on the Y axis?

transform.rotation = Quaternion.Euler(transform.rotation.x, 0, transform.rotation.y);

The code you posted:

transform.rotation = Quaternion.Euler(transform.rotation.x, 0, transform.rotation.y);

Does nothing but locking the Y axis to 0 while keeping the old x and swapping the Z with the old Y, which doesn’t seem right.
To rotate something by 180 deg, you should have that somewhere in the code, right? otherwise how it’s supposed to know how much it should rotate?
As no other code is provided, the player controller or how do you use it, no one will know if that controller is actually working or if you’re using it correctly.

Though, to rotate an object on the Y by 180 deg, you can use the following code:

transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + 180f, transform.rotation.z);

this code will keep the old x and z while changing the y to the opposite direction.

Also you may want to cache the rotation before calling it multiple times, as well as transform, like so:

var rot = transform.rotation;
transform.rotation = Quaternion.Euler(rot.x, rot.y + 180f, rot.z);

Sorry I mean to say that is how I’m rotating it 180 so it should be

transform.rotation = Quaternion.Euler(transform.rotation.x, 180, transform.rotation.y);

However your code has the same problem. Once I start controlling the rotation, the x and z axis stays at zero instead of moving with the object’s parent.

There is no other code controlling the rotation.

Figured it out, the below works. Thanks for the reply

transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, 180, transform.localEulerAngles.z);