What's The Best Way to Change 3 Bools For Real Time Morning, Afternoon And Night
I'm looking for a fairly simple method of changing 3 bools Using real system time in C#:
public bool isMorning = false; public bool isAfternoon = false; public bool isEvening = false;
Answer by NoseKills · Nov 05, 2016 at 07:35 PM
If it can only be Morning, Afternoon or Night (3 states) at any given moment, you should not use 3 booleans (they can represent 8 states). You can avoid bugs such as all 3 booleans becoming true just by choosing your variables in way that prevents it.
using System;
using UnityEngine;
public enum TimeOfDay {
Morning,
Afternoon,
Night,
}
public class TimeOfDayStart {
public int StartHour;
public TimeOfDay Name;
public TimeOfDayStart(int startHour, TimeOfDay name) {
StartHour = startHour;
Name = name;
}
}
public class MyScript : MonoBehaviour {
public TimeOfDay currentTimeOfDay;
public static readonly TimeOfDayStart[] TimeOfDayStartHours = {
new TimeOfDayStart(4, TimeOfDay.Morning),
new TimeOfDayStart(12, TimeOfDay.Afternoon),
new TimeOfDayStart(20, TimeOfDay.Night),
};
void Update () {
var now = DateTime.Now;
currentTimeOfDay = TimeOfDay.Night;
foreach (var tod in TimeOfDayStartHours) {
if (now.Hour >= tod.StartHour) {
currentTimeOfDay = tod.Name;
}
}
Debug.Log(currentTimeOfDay);
}
}
Thanks @Nose$$anonymous$$ills, this looks to be exactly what I need, but how would I access the different times of day from another script?
Thanks @Nose$$anonymous$$ills, This worked great.... say if I wanted to add in a few other parameters like a check for: Breakfast Time Lunch Time Supper time
How would be best to further sub divide this but yet still have the ability to distinguish between: $$anonymous$$orning Afternoon Nighttime
Answer by KnightRiderGuy · Nov 08, 2016 at 01:55 PM
Does anybody know of a good way to further subdivide this method to allow for being able to tell if it is either:
Breakfast Time
Lunch Time
Dinner time