Hi, I am trying to create a 2d game with a town in which some NPCs have a schedule.
Just like Skyrim, the town is a scene and interiors are separate scenes, like tavern is one scene etc. I tried to learn the logic through some research and found some information about it. People say that you need to make the NPC check the time and do its actions according to it. So how am I supposed to make the NPC check the time of day?
I mean, how can I create the “thing” that acts as the “time” and make all NPCs look at it before being where they are supposed to be and do their routine actions?
There’s a few ways you could do this but I would use a coroutine to do it. That’s the thing that acts as the time. It’s like a function you can make repeatedly loop through a set amount of time and trigger events at set intervals. Imagine a game where 24 hours last just 24 minutes, you could set it up the coroutine like this:
public IEnumerator DayCoroutine()
{
// The timer
float elapsedTime = 0;
// 24 minutes expressed in seconds
float twentyFourMinsInSeconds = 60 * 24;
// 7 minutes in seconds
float sevenAM = 60 * 7;
// 9 minutes in seconds
float nineAM = 60 * 9;
// 18 minutes in seconds
float sixPM = 60 * 18;
// 22 minutes in seconds
float tenPM = 60 * 22;
bool wokeUp = false;
bool wentToWork = false;
bool wentHome = false;
bool wentToSleep = false;
// Loop forever
while (true)
{
// Reset the timer to zero
elapsedTime = 0;
// Reset the bools for a new day
wokeUp = false;
wentToWork = false;
wentHome = false;
wentToSleep = false;
while (elapsedTime < twentyFourMinsInSeconds)
{
if (wokeUp == false && elapsedTime > sevenAM)
{
// A function that wakes your character up
WakeUp();
// Set the bool to true so we can stop checking this.
wokeUp = true;
}
else if (wentToWork == false && elapsedTime > nineAM)
{
// A function that wakes your character up
GoToWork();
// Set the bool to true so we can stop checking this.
wokeUp = true;
}
else if (/* not come home by 6 pm then come home */)
else if (/* not asleep by 10 pm then go to sleep */)
// Progress the coroutine to the next frame.
yield return null;
}
yield return null;
}
And you can trigger the coroutine from the Start function like this:
void Start()
{
StartCoroutine(DayCoroutine();
}
That’s not the tidiest example, but basically something along those lines should work.