Coroutine with C#

Godot Version

4.2

Question

Hi I’ve been looking for an example of creating and running a coroutine with c# in godot. I’ve checked out the gdscript reference documentation but am not sure how to translate that for c# syntax.

Searches online haven’t provided me with any examples either so I was curious if anyone had an example of creating and starting a coroutine with a simple timer on it as reference? Thank you for your help.

1 Like

What you trying do with your coroutine?
some task can be done with Tween,

Hi thanks for the reply. This is a general knowledge question as I was familiar with using coroutines in Unity but when I was curious about how to use them in godot with C# I couldn’t find any examples. At the moment I don’t need to run one but I will keep tween in mind. I was just hoping for a code example on how to declare a coroutine and how to start it in godot using C#

1 Like

I manage to do like this

using Godot;
using System.Collections;
using System.Threading.Tasks;

public partial class Coroutine : Node2D
{

    public override async void _Process(double delta)
    {
        if (Input.IsActionJustPressed("ui_accept"))
        {
            foreach (var _ in Fade())
            {
                await Task.Delay(100);
            }
        }
    }

    IEnumerable Fade()
    {
        Color c = Modulate;
        for (float alpha = 1f; alpha >= 0f; alpha -= 0.1f)
        {
            c.A = alpha;
            Modulate = c;
            yield return null;
        }
    }
}
1 Like

Thank you, I’ve seen examples of calling it in a loop. It if you make a coroutine that you simply want to execute with an await how would you call it? In unity it was StartCoroutine(name) to fire off a coroutine.

I based on this Unity - Manual: Coroutines
you start “Fade()” with

 foreach (var _ in Fade())      
          await Task.Delay(100);
1 Like

even more similar to Unity:

using Godot;
using System.Collections;

public partial class Coroutine : Node2D
{

    public override void _Process(double delta)
    {
        if (Input.IsActionJustPressed("ui_accept"))
        {
            StartCoroutine(Fade());
        }
    }

    IEnumerable Fade()
    {
        Color c = Modulate;
        for (float alpha = 1f; alpha >= 0f; alpha -= 0.1f)
        {
            c.A = alpha;
            Modulate = c;
            yield return null;
        }
    }

    public static async void StartCoroutine(IEnumerable objects)
       {
        var mainLoopTree = Engine.GetMainLoop();
        foreach (var _ in objects)
        {
            await mainLoopTree.ToSignal(mainLoopTree, SceneTree.SignalName.ProcessFrame);
        }
    }
}
1 Like

Thank you so much that was very helpful. And thank you for your patience and understanding.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.