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()
一样发生阻塞。如果你希望保证调用时不发生阻塞,就需要确保请求加载和获取资源之间留够时间,或者也可以先手动进行状态检查。
示例
下面这个例子演示的是如何进行场景的后台加载。按下按钮后就会生成一个敌人。敌人使用的是 _onready
时加载的 Enemy.tscn
,按下按钮时进行实例化。该场景的路径为 "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);
}