Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create function flows in Unity/C#

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading