|
1 | 1 | extends Node2D
|
2 | 2 |
|
3 |
| -var thread = Thread.new() |
| 3 | +var thread: Thread |
4 | 4 |
|
5 |
| -# This function runs in a thread! |
6 |
| -# Threads always take one userdata argument |
7 |
| -func _bg_load(path): |
| 5 | +func _on_load_pressed(): |
| 6 | + if is_instance_valid(thread) and thread.is_started(): |
| 7 | + # If a thread is already running, let it finish before we start another. |
| 8 | + thread.wait_to_finish() |
| 9 | + thread = Thread.new() |
| 10 | + print("START THREAD!") |
| 11 | + # Our method needs an argument, so we pass it using bind(). |
| 12 | + thread.start(_bg_load.bind("res://mona.png")) |
| 13 | + |
| 14 | + |
| 15 | +func _bg_load(path: String): |
8 | 16 | print("THREAD FUNC!")
|
9 |
| - # Load the resource |
10 |
| - var tex = ResourceLoader.load(path) |
11 |
| - # Call _bg_load_done on main thread |
12 |
| - call_deferred("_bg_load_done") |
13 |
| - return tex # return it |
| 17 | + var tex = load(path) |
| 18 | + # call_deferred() tells the main thread to call a method during idle time. |
| 19 | + # Our method operates on nodes currently in the tree, so it isn't safe to |
| 20 | + # call directly from another thread. |
| 21 | + _bg_load_done.call_deferred() |
| 22 | + return tex |
14 | 23 |
|
15 | 24 |
|
16 | 25 | func _bg_load_done():
|
17 |
| - # Wait for the thread to complete, get the returned value |
| 26 | + # Wait for the thread to complete, and get the returned value. |
18 | 27 | var tex = thread.wait_to_finish()
|
19 |
| - # Set to the sprite |
20 |
| - get_node(^"Sprite2D").set_texture(tex) |
| 28 | + print("THREAD FINISHED!") |
| 29 | + $Sprite2D.set_texture(tex) |
| 30 | + # We're done with the thread now, so we can free it. |
| 31 | + thread = null # Threads are reference counted, so this is how we free it. |
21 | 32 |
|
22 | 33 |
|
23 |
| -func _on_load_pressed(): |
24 |
| - if thread.is_active(): |
25 |
| - # Already working |
26 |
| - return |
27 |
| - print("START THREAD!") |
28 |
| - thread.start(self, "_bg_load", "res://mona.png") |
| 34 | +func _exit_tree(): |
| 35 | + # You should always wait for a thread to finish before letting it get freed! |
| 36 | + # It might not clean up correctly if you don't. |
| 37 | + if is_instance_valid(thread) and thread.is_started(): |
| 38 | + thread.wait_to_finish() |
| 39 | + thread = null |
0 commit comments