godot-demo-projects/loading/threads/thread.gd

42 lines
1.2 KiB
GDScript3
Raw Normal View History

2022-12-13 16:51:04 +01:00
extends Control
2014-02-10 02:10:30 +01:00
2022-06-09 03:53:45 +02:00
var thread: Thread
2014-02-10 02:10:30 +01:00
2022-12-13 16:51:04 +01:00
2022-06-09 03:53:45 +02:00
func _on_load_pressed():
if is_instance_valid(thread) and thread.is_started():
# If a thread is already running, let it finish before we start another.
thread.wait_to_finish()
thread = Thread.new()
print("START THREAD!")
# Our method needs an argument, so we pass it using bind().
thread.start(_bg_load.bind("res://mona.png"))
func _bg_load(path: String):
2014-02-10 02:10:30 +01:00
print("THREAD FUNC!")
2022-06-09 03:53:45 +02:00
var tex = load(path)
# call_deferred() tells the main thread to call a method during idle time.
# Our method operates on nodes currently in the tree, so it isn't safe to
# call directly from another thread.
_bg_load_done.call_deferred()
return tex
2014-02-10 02:10:30 +01:00
func _bg_load_done():
2022-06-09 03:53:45 +02:00
# Wait for the thread to complete, and get the returned value.
2014-02-10 02:10:30 +01:00
var tex = thread.wait_to_finish()
2022-06-09 03:53:45 +02:00
print("THREAD FINISHED!")
2022-12-13 16:51:04 +01:00
$TextureRect.texture = tex
2022-06-09 03:53:45 +02:00
# We're done with the thread now, so we can free it.
2022-12-13 16:51:04 +01:00
thread = null # Threads are reference counted, so this is how we free them.
2014-02-10 02:10:30 +01:00
2022-06-09 03:53:45 +02:00
func _exit_tree():
# You should always wait for a thread to finish before letting it get freed!
# It might not clean up correctly if you don't.
if is_instance_valid(thread) and thread.is_started():
thread.wait_to_finish()
thread = null