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...
邏輯偏好
可曾想過問題 X 要用策略 Y 還是 Z 來解決?本篇文章將探討關於這類難題的各種主題。
先新增節點還是先修改屬性?
運作時使用腳本初始化節點時,你可能需要對節點的名稱、位置等屬性進行修改。常見的糾結點在於,你應該什麼時候去修改?
最佳實踐是在節點加入場景樹之前修改它的值。部分屬性的 setter 程式碼會更新其他對應的值,這些程式碼可能會很慢!大多數情況下,這些程式碼不會對遊戲的效能產生影響,但對於程式式生成之類的高負載場景下,就可能讓遊戲執行得極其緩慢。
基於這些原因,通常最佳實務是在將節點加入場景樹之前設定其初始值。但也存在一些例外情況,某些值在加入場景樹之前 無法 設定,例如設定全域位置。
載入 (Load) vs. 預載入 (Preload)
在 GDScript 中,有一個全域的 preload 方法。通過這個方法可以儘量將「載入」操作提早執行,並避免在效能敏感的程式執行時載入資源。
相對地,load 方法則只會在碰到 load 陳述式時才載入資源。也就是說,load 方法只會就地載入資源,而當在敏感的處理過程中使用 load 就會讓程式變慢。 load() 方法同時也是 ResourceLoader.load(path) 的別名,這個方法可以在 所有 腳本語言中存取。
那麼,Load 與 Preload 實際上到底差在哪裡呢?什麼時候又該用什麼呢?請看看這個範例:
# my_buildings.gd
extends Node
# Note how constant scripts/scenes have a different naming scheme than
# their property variants.
# This value is a constant, so it spawns when the Script object loads.
# The script is preloading the value. The advantage here is that the editor
# can offer autocompletion since it must be a static path.
const BuildingScn = preload("res://building.tscn")
# 1. The script preloads the value, so it will load as a dependency
# of the 'my_buildings.gd' script file. But, because this is a
# property rather than a constant, the object won't copy the preloaded
# PackedScene resource into the property until the script instantiates
# with .new().
#
# 2. The preloaded value is inaccessible from the Script object alone. As
# such, preloading the value here actually does not provide any benefit.
#
# 3. Because the user exports the value, if this script stored on
# a node in a scene file, the scene instantiation code will overwrite the
# preloaded initial value anyway (wasting it). It's usually better to
# provide `null`, empty, or otherwise invalid default values for exports.
#
# 4. Instantiating the script on its own with .new() triggers
# `load("office.tscn")`, ignoring any value set through the export.
@export var a_building : PackedScene = preload("office.tscn")
# Uh oh! This results in an error!
# One must assign constant values to constants. Because `load` performs a
# runtime lookup by its very nature, one cannot use it to initialize a
# constant.
const OfficeScn = load("res://office.tscn")
# Successfully loads and only when one instantiates the script! Yay!
var office_scn = load("res://office.tscn")
using Godot;
// C# and other languages have no concept of "preloading".
public partial class MyBuildings : Node
{
//This is a read-only field, it can only be assigned when it's declared or during a constructor.
public readonly PackedScene Building = ResourceLoader.Load<PackedScene>("res://building.tscn");
public PackedScene ABuilding;
public override void _Ready()
{
// Can assign the value during initialization.
ABuilding = GD.Load<PackedScene>("res://Office.tscn");
}
}
using namespace godot;
class MyBuildings : public Node {
GDCLASS(MyBuildings, Node)
public:
const Ref<PackedScene> building = ResourceLoader::get_singleton()->load("res://building.tscn");
Ref<PackedScene> a_building;
virtual void _ready() override {
// Can assign the value during initialization.
a_building = ResourceLoader::get_singleton()->load("res://office.tscn");
}
};
預載入允許腳本在載入腳本時處理所有載入. 預載入雖然很有用, 但有時候開發者則並不採用。 為了區分這些情況, 我們可以考慮以下幾點:
如果無法確定何時可以載入腳本, 那麼預載入資源(尤其是場景或腳本)則有可能會導致非預料的多餘載入。 這有可能會導在原始腳本載入時間之上多出意料之外的不確定載入時間。
若可以使用其他東西來代替某個值 (特別是場景的匯出初始化),則預加載這個值就沒有意義。如果平常都是自行製作腳本的話,那麼這一點就並非重要因素。
如果只是想要「匯入」另一個類別資源 (腳本或場景),那麼使用預加載的常數應該是最好的方法。但是,有幾個例外情況下最好不要這麼做:
如果這個「被匯入」的類別可能會變動,那麼它應該是一個屬性,並透過
@export或load()進行初始化(甚至可能延後初始化)。如果腳本需要大量相依性關係,又不想消耗太多記憶體,則可以在執行環境變化時動態地載入或卸載各種相依性關係。如果將資源預載入為常數,那唯一卸載這些資源的方法則是卸載整個腳本。如果這些資源作為屬性來載入,則可以將這些屬性設定為
null並完全刪除對資源的所有參照(擴充自 RefCounted 的型別會讓該資源在指向其的所有參照均已消失時自動釋放記憶體)。
大型關卡:靜態 vs. 動態
如果正在建立一個大型關卡,哪種情況是最合適的?是將關卡建立為一個靜態空間,還是分階段載入關卡, 並根據需要調整世界的內容?
這個嘛,用一句話來回答的話就是,「如果效能有需要的時候。」。其實這種兩難的情況跟一個古老的程式設計問題有關:要對記憶體最佳化還是對速度最佳化?
而最簡單的方法就是使用單一靜態關卡,並一次載入所有東西。但是,依據不同的專案,這樣可能會吃掉很多的記憶體。浪費使用者的 RAM 也會導致程式執行地很慢,或是當電腦嘗試同時做其他事情時讓遊戲當機。
無論如何,我們都應該將大型場景切分成許多小的場景 (來提升素材的可復用性)。開發人員可以設計一個節點,來即時管理資源與節點的建立/載入與刪除/取消載入。有大型且多樣化環境的遊戲,或是會連續產生多個元素的遊戲,通常會使用這種策略來減少浪費記憶體。
另一方面, 編一個動態系統則更加複雜, 這會使用更多的編程邏輯, 並借此增加出錯和bug的機會。如果不夠小心的話,編出的系統技術債務可能會像吹氣球一樣增加。
因此,最好的做法應該是…
在小型遊戲中使用靜態關卡.
在開發中型/大型遊戲時,如果有時間/資源,可以去建立一個可以對節點和資源的管理進行編碼的庫或外掛。若長期對其進行打磨以提高可用性和穩定性,那麼它可能會演變成跨專案的可靠工具。
對於一款中/大型遊戲,可採用動態邏輯,因為你擁有編程技能,卻沒有時間或資源去完善程式碼(畢竟要完成遊戲),後續可能進行重構,將程式碼外移到外掛中。
有關在執行時間切換場景的各種方法的範例,請參考 「手動更改場景」 說明文件。