Home > Enterprise >  Create function flows in Unity/C#
Create function flows in Unity/C#

Time:03-18

I am having a bunch of functions that I want happening in a specific order after eachother. Some of the functions are IEnumerators which needs to be finished before next function starts. This would be a representation of what I want:

private void MainFunction()
{
    StartCoroutine(FunctionA());
    FunctionB();  // Function A must completely finished before running this
{

However, this starts function A first and then as soon as function A returns a null/WaitForSeconds etc function B will start before function A has completed.

One way I found is to just put function B at the end of function A. This however creates a nest of functions (since I in my real code have 5-6 functions I want running after eachother in MainFunction) which makes the code very hard to follow after a few steps:

private void MainFunction()
{
    StartCoroutine(FunctionA());
{

private IEnumerator FunctionA()
{
    // Do stuff here
    yield return null;

    FunctionB();
{

Is there a way to create this more nicely which would also be more easy to follow? Preferably some trick to get the first code snippet I posted to work?

CodePudding user response:

There are probably many approaches for this and all have their pros and cons.

I'd say probably the easiest one would be to simply wrap this into a "mother" routine and do e.g.

public void MainMethod()
{
    StartCoroutine(MainMethodRoutine());
}

private IEnumerator MainMethodRoutine()
{
    yield return FunctionA();

    FunctionB();

    ...
}

Or as said you could use callbacks and rather do e.g.

public void MainMethod()
{
    StartCoroutine(FunctionA(() =>
    {
        FunctionB();

        ...
    }));
}

private IEnumerator FunctionA(Action whenDone = null)
{
    ...

    whenDone?.Invoke();
}

In my opinion this however already gets a little bit more ugly and harder to read and debug.

  • Related