- Home /
Is there a way i can make a function that gets called every round in a turn based RPG?
I'm currently making a turn based RPG and i want a way to track how many rounds have passed since a certain action.
void Update(); gets called every frame and you can access it from any script.
I want to do the same thing but it'll be something like NewRound(); and gets called every round.
Maybe there's a better way to do this idk. Any answers would be much appreciated :)
How do you start a new round in your game? Do you wait for e.g. a "space" press? If so, you can create a global script RoundHelper and put your NewRound() there. Then you just call RoundHelper.NewRound() if someone presses space.
$$anonymous$$aybe this post can give you a better idea of whats possible otherwise
Answer by Duckocide · Oct 26, 2020 at 10:34 AM
Look at Coroutines. They are a great way of running things in parallel to the main unity lifecycle.
So, in your Monobehaviour component add the following to the "OnEnabled" method, something like (all this code is untested and typed in to the forum straight!)...
StartCoroutine(MyTurnEngineCR());
Then add a private IEnumerator method with something like...
public bool turnComplete = false;
public int turnCount = 0;
private bool _turnEngineActive = true;
private IEnumerator MyTurnEngineCR()
{
while(_turnEngineActive)
{
yield return new WaitForEndOfFrame();
turnCount += 1;
Debug,Log($"Turn {turnCount} started...");
// Has the turn completed?
while (!turnComplete)
{
yield return new WaitForEndOfFrame();
}
turnComplete = false;
Debug,Log($"Turn {turnCount} Completed!");
}
This will sit there waiting every frame to see if the boolean "turnOver" has been set. If it has, it will clear that flag and increment the turnCount. The yield lines are really important as they hand processing back to the main unity thread. Generally (other than what you do in them), Coroutines have little performance cost (I often use them for enemy AI's).
The private _turnEngineActive bool is simply to keep the coroutine looping (if you set it false, it will stop once a turn is over).
Hope this helps. Coroutines are important for anything that can happen outside of the Update() etc unity cycle loop. Recommend you read up on them. Once you get used to them, they are so so useful for all sorts of things like AI, monitoring and decision making in a game.
Your answer

Follow this Question
Related Questions
Turn-based vehicle physics 1 Answer
Is this the right program 0 Answers
Business simulation in Unity 1 Answer
Detect the same variable from multiple scripts 2 Answers
how to create turns between 2 players 0 Answers