Locking rotation on local axis

Hello.
I need by physic body be able to rotate only by local X axis.

Z axis should be fixed; (same as rigitbody rotation constraints but local)
Y axis controlled by external script.

This is solution I have so far

Vector3 a = bike.transform.localRotation.eulerAngles;

		a.y = transform.localRotation.eulerAngles.y;		
		a.z = 0f;

		bike.transform.localRotation =  Quaternion.Euler(a);

But problem, that “bike” not able to rotate by X axis only from 90 to 270. It not able to flip back. I’m not very good with Quaternion’s that’s why I asking fro help. Thanks!

I used this in one of my scripts, hope it helps:

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

Here is a second try at a solution. What it does is get the magnitude of the current rotation and then builds a angle/axis rotation around the local ‘x’ axis of that magnitude. Note since magnitude is unsigned, you will always have rotation in the same direction. It would take some work to produce a ‘signed magnitude’ so that the rotation could be reversed.

function FixedUpdate() {
	var v3 = Vector3(rigidbody.angularVelocity.magnitude, 0.0, 0.0);
	v3 = transform.TransformDirection(v3);
	rigidbody.angularVelocity = v3;
}

Note this solution does not prevent the object from being turned. If you want to keep the object align to the world axes (i.e. cannot be turned at all), you can add this line to Update():

    transform.rotation = Quaternion.FromToRotation(transform.right, Vector3.right) * transform.rotation;