Orbit over 1 hour with acurate timer

I’m trying to create a 2D day & night cycle with a sun orbiting a planet around the z axis taking an hour to fully rotate. I need a timer to capture the hours / days past since the game started which syncs perfectly with the current orbit of the sun.

So far I have created the rotation and it works pretty well, however my timer goes off track by the second orbit. Is there a way to sync my hour, day floats with the rotation of the sun?

Cheers

	private float rotateTime = 1.0f; // 1 hour.
	private float degressToRotate;

	public float hours;
	public float days;

	void Start() 
	{
		InvokeRepeating("AddHours", 150.0f, 150.0F);
	}

	
	void Update () 
	{
		degressToRotate = (360/(rotateTime*60*60)) * Time.deltaTime;
		gameObject.transform.Rotate(0f, 0f, degressToRotate);
	}

	void AddHours()
	{
		if(hours >= 24f) 
		{
			hours = 0f;
			gameObject.transform.Rotate(0f, 0f, 0f);
			days++;
		}
		else {
			hours++;
		}
	}

Rotation, hour and day are not values you should be setting separately - they’ll get out of sync eventually, no matter how accurate you are with how you try to sync them.

Instead, read of Time.time, and use that to set each of the other values. This example uses a public float field that gives the length of day, and uses Gizmos to show that the correct day and hour is being set.

Note that this will have to be attached to the point of rotation, and whatever’s rotating needs to be a child object of that. That’s what you’re already doing, but just to be safe.

public float dayLength;
float rotationSpeed;

void Start()
{
    rotationSpeed = (1 / dayLength) * 360f;
}

// Update is called once per frame
void Update()
{
    transform.eulerAngles = new Vector3(0, 0, Time.time * rotationSpeed);
}

private int GetHour()
{
    return (int)((Time.time / (dayLength / 24)) % 24);
}

private int GetDay()
{
    return (int)(Time.time / dayLength);
}

void OnDrawGizmos()
{
    if (Application.isPlaying)
        UnityEditor.Handles.Label(transform.position, "Day: " + GetDay() + " Hour: " + GetHour() + " Real time: " + Time.time);
}