Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

後臺載入

通常,遊戲需要非同步載入資源。當切換遊戲的主場景時(例如,進入新的關卡),您可能想要顯示一個載入畫面,其中包含一些正在進行的指示,或者您可能希望在遊戲過程中載入其他資源。

標準載入方法(ResourceLoader.load 或 GDScript 更簡單的:ref:load <class_@GDScript_method_load>)會阻塞您的線程,讓您的遊戲在載入資源時顯得無回應。

解決這個問題的一種方法是使用「ResourceLoader」在後台執行緒中非同步載入資源。

建立 ResourceFormatLoader

通常,您使用 ResourceLoader.load_threaded_request <class_ResourceLoader_method_load_threaded_request> 對載入路徑資源的請求進行排隊,然後將在背景的執行緒中載入。

您可以使用 ResourceLoader.load_threaded_get_status <class_ResourceLoader_method_load_threaded_get_status>` 檢查狀態。可以透過 Progress 傳遞一個陣列變數來取得進度,該變數將傳回一個包含百分比的單元素陣列。

Finally, you retrieve loaded resources by calling ResourceLoader.load_threaded_get.

一旦你呼叫“load_threaded_get()”,資源要么在後台完成加載並立即返回,要么加載將像“load()”一樣在此時阻塞。如果您想保證這不會阻塞,您要么需要確保請求加載和檢索資源之間有足夠的時間,要么需要手動檢查狀態。

範例

此範例示範如何在背景載入場景。我們將有一個按鈕,按下時會生成一個敵人。敵人將是“Enemy.tscn”,我們將在“_ready”上載入它並在按下時實例化。路徑為“Enemy.tscn”,位於“res://Enemy.tscn”。

首先,我們將啟動一個請求來載入資源並連接按鈕:

const ENEMY_SCENE_PATH : String = "Enemy.tscn"

func _ready():
    ResourceLoader.load_threaded_request(ENEMY_SCENE_PATH)
    self.pressed.connect(_on_button_pressed)

現在按下按鈕時將呼叫“_on_button_pressed”。此方法將用於生成敵人。

func _on_button_pressed(): # Button was pressed
    # Obtain the resource now that we need it
    var enemy_scene = ResourceLoader.load_threaded_get(ENEMY_SCENE_PATH)
    # Instantiate the enemy scene and add it to the current scene
    var enemy = enemy_scene.instantiate()
    add_child(enemy)