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.

Variant 類別

關於

Variant 是 Godot 中最重要的資料型別。在 64 位元平台上僅佔用 24 位元組(32 位元平台為 20 位元組),能夠儲存幾乎所有引擎資料型別。Variant 通常不會長時間持有資料,主要用途為溝通、編輯、序列化,以及一般資料的傳遞。

Variant 可以:

  • 儲存幾乎所有資料型別。

  • 在多個 Variant 之間進行運算(GDScript 以 Variant 作為其原生/基本資料型別)。

  • 可進行雜湊,能迅速與其他 Variant 比較。

  • 可用於安全地在各種資料型別間轉換。

  • 可用於抽象化方法呼叫及其參數(Godot 以 Variant 匯出其所有函式)。

  • 可用來延遲呼叫或在線程間傳遞資料。

  • 可序列化為二進位格式,儲存至磁碟或經由網路傳輸。

  • 可序列化為文字,用於列印數值或可編輯的設定。

  • 可作為匯出屬性,讓編輯器能進行通用編輯。

  • 可用於字典、陣列、剖析器等結構。

基本上,多虧了 Variant 類別,撰寫 Godot 本身變得容易許多,因為它讓 C++ 中少見的高度動態結構能輕鬆實現。現在就來好好認識 Variant 吧。

備註

Variant 內除了 Nil 與 Object 以外的所有型別, 都不能null ,必須始終儲存有效的值。因此這些型別被稱為 不可為 null 的型別。

Variant 型別中的一種是 Nil,僅能儲存 null。因此,即使除了 Nil 與 Object 之外的 Variant 型別皆不可為 null,Variant 仍有可能包含 null 值。

參考資料

Variant 型別清單

Variant 支援以下型別:

型別

說明

Nil(僅能儲存 null

可為 null 型別

bool

int

float

String

Vector2

Vector2i

Rect2

AABB 的 2D 對應型別

Rect2i

Vector3

Vector3i

Transform2D

Vector4

Vector4i

Plane

Quaternion

AABB

Rect2 的 3D 對應型別

Basis

Transform3D

Projection

Color

StringName

NodePath

RID

Object

可為 null 型別

Callable

Signal

Dictionary

Array

PackedByteArray

PackedInt32Array

PackedInt64Array

PackedFloat32Array

PackedFloat64Array

PackedStringArray

PackedVector2Array

PackedVector3Array

PackedColorArray

PackedVector4Array

容器:Array 與 Dictionary

ArrayDictionary 都是透過 Variant 實作。Dictionary 可將任意型別作為鍵對應至其他任意型別。Array 則僅儲存 Variant 的陣列。當然,Variant 內也能再儲存 Dictionary 或 Array,讓其更加靈活。

Modifications to a container will modify all references to it. A Mutex should be created to lock it if multi-threaded access is desired.

參考資料