set object's rotation.y to camera's rotation.y

so i want to rotate this object so that its rotation on y axis is the same as the camera’s y axis rotation.

my current code works, but when the object is rotated 180 on y axis, it starts moving backward when forward button is pressed, it moves right when left button is pressed.
when i rotate the object again, the movement gets fixed.

Quaternion newRotation = transform.rotation;
newRotation.y = cam.rotation.y;
transform.rotation = newRotation;

transform.Translate(speed*Input.GetAxis("Horizontal"),0,speed*Input.GetAxis("Vertical"));

what is the correct way to set object’s rotation to camera’s rotation? how do i set eular angles instead of quaternions?

@vishesh-l, I think you sense, and I’ll confirm, that this:

newRotation.y = cam.rotation.y

Isn’t going to do what you expect. The member y (and the others, x, z and w) are part of the quaternion, and don’t represent the rotation by axis. A quaternion, crudely stated, is a vector indicating direction, taking the function of a yaw and pitch combination, while w represents the roll rotation angle. Manipulating the internals of the quaternion will generate odd results unless you use the algebra associated with quaternions to do it.

That said, you probably already know that you can get the euler angles through the eulerAngles property, which do represent angles of rotation on the X, Y and Z axis, which are the only way of reading what you need.

To “set” the eular angles of a quaternion, you use the static member Quanternion.Eular(x,y,z) to fashion a NEW quaternion that replaces or is copied into the existing one. Since you must supply the x and z angles, you’ll need a source for them, perhaps not the camera, while the Y coordinate orientation is taken from the camera.

While I don’t know your specific code circumstances, something like this might work:

Quatnerion newRotation
= Quaternion.Eular( transform.rotation.eularAngles.x,
cam.rotation.eularAngles.y,
transform.rotation.eularAngles.z );
transform.rotation = newRotation;