Reputation: 10551
I have to show complete 24 hours cycle in Unity3d Scene. Where different kind of task will be executed in different Times.
Suppose
Now, I have some basic animation e.g., car, Aeroplane and door etc.,. Now I am confuse that how to play and stop my animation according to the time. And time can also be changed manually using GUI. If currently 6pm (animation working) then user can switch to 8am to view 8am time's animation. And User can also fast the timing to view complete hours in a single minutes or in an hour.
I can use if/else in Update Events but I guess this is not the right way to do and will be very difficult if I require to show significant number of works in different time duration (which means significant number of if/else statements). Just like below
void Update(){
if(time =1){
//logic
}
if(time =2){
//logic
}
if(time =3){
//logic
}
...//so on, tedious way
...//and also not possible if time require between the hours, suppose 06:06pm
}
What to do ? How to handle this?
Upvotes: 1
Views: 91
Reputation: 2016
Well, I think it is code design issue. I recommend to use some kind of Observer pattern. You need to subscribe IObersver
objects in main controller which will trigger all subscribers on some events, for example each minute, like this:
foreach(IObserver observer in observers) {
observer.Notify();
}
Each observer will check time using it's own schedule. For instance, traffic light observer will check if 1 minute passed from last switch and if yes, then switch light:
public TrafficLight : IObserver {
...
public void Notify() {
if(timePassed > sachedulledTime) {
SwithcLight();
}
}
Using this code design you can add to your controller as many object as you need without even knowing which these objects are and what is their schedule.
Upvotes: 1
Reputation: 3019
There are many ways to do this. if statements are the most unprofessional. I would recommend you to use UnityEvents in this situation.
Let's say I need to trigger stuff at x:00 times. I would create an array of UnityEvents of size 24 and trigger 1 per hour. like this:
public UnityEvent[] hourTrigger; //24 hours
public float oneHour = 120f; //one hour in game is 120 seconds real time
private int hourCounter = 0;
void Start(){
hourTrigger = new UnityEvent[24];
StartCoroutine (HourlyTrigger ());
}
IEnumerator HourlyTrigger(){
//repeat this every oneHour interval
while(true){
hourTrigger[hourCounter].Invoke();
yield return new WaitForSeconds(oneHour);
hourCounter = ++hourCounter % 24;
}
}
Then you can add listeners to any of the triggers and they will automatically get started at appropriate times.
This is just off the top of my head, most probably someone else will post a better solution. Still, one big advantage of this code is that you write this and you will never have to open this script ever again. You can add your scheduled actions and remove them from outside scripts.
Upvotes: 2