+5 votes

I want to know if there is an efficient way to make bigger calculations over multiple frames.
In a project, where I'm currently working on, I need to do some bigger calculations which take almost half a second ore more. right now I spread them with a loop which only does X repetitions.

var x = 10 #process steps per frame
var curent_process_state = 0 
for i in range(x):
    #calculate longer process
    liste[i + current_process_state].calculate_time_consuming_function()
current_process_state += x

This kind of works but I have to approximate a value for x so that the game runs smooth.
It would be great if I could do it like:

func myFunc():
    for e in list:
execute myFunc for 0.02 seconds

Is there a way to do so in GDscript?

in Engine by (333 points)

1 Answer

+5 votes

A way that I use is Thread.
Then, a yield with idle frame in it

Here my code:

var source_list = {}; var thread = Thread.new()

func _ready():
        thread.start(self, "_test_de_thread", null)

func _test_de_thread(trash):
        var list1
        var list2
        while (true):
                list1 = get_tree().get_nodes_in_group("police")
                list2 = get_tree().get_nodes_in_group("civilian")
                print("Frame: ", get_tree().get_frame(), "group police: ", list1, ", group civilian: ", list2, ", List:", source_list)
                yield(get_tree(), "idle_frame")
by (98 points)
Thank you!  This seems to be exactly what i was looking for.
I didn't try it out until now but I will, soon.   ;)
I tried it out now.
It seems that the yield() function isn't even necessary. As I understand it only makes sure that the while loop only repeats once per frame. Is that correct or is there a deeper functionality behind it?
I was using this to prevent too heavy compute at same time, because if you dont, it can slow fps (less than without thread)

Interacting with scene tree is not thread safee, so this code may result in error

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.