Search code examples
coroutinegodotgdscript

How to create a custom "update" function in Godot using GDscript?


I want something somewhat equivalent to this code that was written in C# for Unity. I want to be able to call an "diy_update()" function whenever I want and end that process according to a Boolean.

    void Start()
    {
        StartCoroutine(DIY_Update());
    }

    IEnumerator DIY_Update()
    {
        while (true)
        {
            if(randomBoolean)
            {
                break;
            }
            yield return null;
        }
    }

This obviously make the code stop and await until DIY_Update() finishes, therefor is not what I wanted.

extends Node

func _ready():
    await(DIY_Update())

func DIY_Update():
    while true:
        if random_boolean():
            break
        await(null)


Solution

  • In Unity doing yield return null; will have the execution of the coroutine resumes in the following frame.

    We can do that in Godot by awaiting the process_frame signal:

    await get_tree().process_frame
    

    I also want to point out that you can control if Godot calls _process by calling set_process.