Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
後臺載入
通常,遊戲需要非同步載入資源。當切換遊戲的主場景時(例如,進入新的關卡),您可能想要顯示一個載入畫面,其中包含一些正在進行的指示,或者您可能希望在遊戲過程中載入其他資源。
標準的載入方法(ResourceLoader.load 或 GDScript 中較簡單的 load)會阻塞您的執行緒,導致您的遊戲在載入資源時看起來沒有回應。
其中一種解決方式是使用 ResourceLoader 在背景執行緒中非同步載入資源。
使用 ResourceLoader
通常,你可以使用 ResourceLoader.load_threaded_request 來將指定路徑的資源載入請求排入佇列,這些資源會在背景執行緒中載入。
你可以透過 ResourceLoader.load_threaded_get_status 來檢查狀態。進度可以透過 progress 參數傳入一個陣列變數,該變數會回傳一個包含百分比的單元素陣列。
最後,你可以呼叫 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)
using Godot;
public partial class MyButton : Button
{
private const string EnemyScenePath = "Enemy.tscn";
public override void _Ready()
{
ResourceLoader.LoadThreadedRequest(EnemyScenePath);
Pressed += OnButtonPressed;
}
}
現在,當按鈕被按下時會呼叫 _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)
private void OnButtonPressed() // Button was pressed.
{
// Obtain the resource now that we need it.
var enemyScene = (PackedScene)ResourceLoader.LoadThreadedGet(EnemyScenePath);
// Instantiate the enemy scene and add it to the current scene.
var enemy = enemyScene.Instantiate();
AddChild(enemy);
}