something happens when object reaches specific rotation value

hey guys, i’m new in unity, and i have a script where i want an object to rotate and when it reaches a specific value something happens. The object is rotating correctly, but the if statement isn’t detecting the rotation, and i think its related to the numbers between the inspector and the script. Thanks for reading and the help :slight_smile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotationScript : MonoBehaviour
{
	
	public GameObject myObject;
	public float x, y;
	public float z = -90;

    void Update()
    {
        if ( Input.GetKeyDown(KeyCode.E))
		{
			myObject.transform.Rotate(x, y, z);
		}
		if (myObject.transform.rotation.z == -180)
		{
				//Something Happens
		}
    }

I believe the issue is to do with Floating Point precision. The thing is that, while FPs have a very high range, their accuracy leaves something to be desired. It’s unlikely that the number is exactly 180 but you could do something like:

if (MathF.Round(myObject.transform.rotation.z) == -180)

Alternatively, look up Mathf.Epsilon to find an alternative solution and understand a bit more about accuracy in floating point numbers.

Ah yes, rotation states, my favorite ;D

jokes aside - there is more than one issue here. First is what @SurreyMuso already pointed out. The probability of hitting a round number on a float calculation is really really really low.

However as you noticed the solution proposed by surrey is also not really reliable.

This is (most probably) due to euler Angles. While Euler Angles seem straight forward they have one crucial issue: Every rotation of an Object can be always displayed with more than one set of euler angles. The only unique and safe way to treat a rotation in that regard is if you use Quaternions (what Unity internally does). A Quaternion is always unique for one 3D rotation.

So what can we do? Imo the easiest thing you can do here is to calculate the Angle between for example your transform.forward axis and Vector3.up.
Example case: if that angle comes to zero you know that your transform is directly pointing upwards with it’s z-Axis. (This however would not say anything about the rest of its rotation → you’d need another check like this to make sure it is rotated in one specific way)