Hi, I’m very new to C# and I have a simple script set up to rotate an object around the z axis by 0.05f every frame.
I am trying to print the resulting value by using
print(transform.eulerAngles.z);
However, the result looks like this - it randomly jumps between numbers. Right now the inspector is showing 177 degrees on the z rotation while the last few frames of the console say:
347.9419
177.861
347.9341
177.911
347.9282
I definitely only have one print operation as follows:
void Rotate()
{
float rotation = 0.05f;
float angle = 10f;
print(transform.eulerAngles.z);
transform.Rotate(Vector3.forward, rotation, Space.World);
}
Ideally I would just like it to consistently print the current rotation using whichever method. Any assistance would be appreciated.
well you have 2 issues at hand. First is that floats only have a certain accuracy. So all additions/substractions might result in a different number than you’d expect. So 1 - 0.5 = 0.5 + 0.5 = 0.999999999 for example.
The other thing is euler angles itself. For this you have to understand that a single rotation might have different representations in euler angles. For that reason when rotating an object you can not guarantee that the resulting euler representation looks the same. It will be the same rotation be might differ a lot. Only Quaternions will always be the same for each rotation.
In my experience you can work around this issue by making sure that you only ever have one angle of x,y,z be unequal zero. This can for example be achived by introducing a parent transform and to the only use the local rotation of the object you actually want to rotate.
if that is not an option for you you should share more details on your project and what you are trying to do so that one can understand why you need this value. For most appications it is not (and should not be) necessary to look at the exact euler angle of an axis over multiple frames.
Thanks all for your assistance, I’ve managed to fix and then reproduce the problem again.
I was calling Rotate() from the update method, I changed that to if(true) {Rotate();}. Now I’m getting consistent and accurate results in the console.
Print is still being called every frame but not directly from the update method. This seems like a bug?
@koroveshil from unity’s documentation
Transform.eulerAngles represents rotation in world space. When viewing the rotation of a GameObject in the Inspector, you may see different angle values from those stored in this property. This is because the Inspector displays local rotation
To do what you are trying to do you can do something like
Debug.Log(transform.rotation.z)
Hope this helps