Restricting rotation to the y axis in C#

I am trying to keep my enemy object from rotating on the z and x axis while patrolling.
I was using this set up in unity script but want to change it to C#

RotateToward(target.position, turnSpeed);
	transform.rotation.x = 0;
	transform.rotation.z = 0;

I have so far tried the following in C# with no success

    Quaternion enmeyRotationX = transform.rotation;
	Quaternion enmeyRotationZ = transform.rotation;

	RotateToward(target.position, turnSpeed);

	enmeyRotationX.x = 0f;

	enmeyRotationZ.z = 0f;

	transform.rotation = enmeyRotationX;

	transform.rotation = enmeyRotationZ;

Searching through the Q&A on these boards I found many solutions but they also appear to be for Jscript and I dont know how to translate it.

Many thanks

I’m afraid Quaternions don’t work the way you think they do. If you wanted to restrict a transform’s rotation, you could use something like this-

Vector3 eulerAngles = transform.rotation.eulerAngles;
eulerAngles = new Vector3(0, eulerAngles.y, 0);
transform.rotation = Quaternion. Euler(eulerAngles);

Alternatively, you could automatically squash the angle down in the previous step-

Vector3 correctTarget = new Vector3(target.position.x, transform.position.y, target.position.z);
transform.LookAt(correctTarget);

and not worry about the exact Quaternions at all! There are very few situations where you would want to manually change the contents of a quaternion. Unless you are very familiar with the (literally complex) mathematics of them, there’s no point trying, since the Quaternion class provides plenty of utilities for creating and modifying quaternions in ways which are much easier to understand!

syclamoth’s answer is correct, but here is a direct translation of the (incorrect) JavaScript:

RotateToward(target.position, turnSpeed);
var r = transform.rotation;
r.x = 0;
r.z = 0;
transform.rotation = r;

This will leave you with an incorrect w, just as the JavaScript does, but hopefully it expains what was wrong with your attempts.

Thanks guys worked wonders and makes my script look allot cleaner too