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.

Resource

繼承: RefCounted < Object

被繼承: Animation, AnimationLibrary, AnimationNode, AnimationNodeStateMachinePlayback, AnimationNodeStateMachineTransition, AudioBusLayout, AudioEffect, AudioStream, BitMap, BoneMap, ButtonGroup, CameraAttributes, ColorPalette, Compositor, CompositorEffect, CryptoKey, Curve, Curve2D, Curve3D, EditorNode3DGizmoPlugin, EditorSettings, Environment, FoldableGroup, Font, GDExtension, GLTFAccessor, GLTFAnimation, GLTFBufferView, GLTFCamera, GLTFDocument, GLTFDocumentExtension, GLTFLight, GLTFMesh, GLTFNode, GLTFPhysicsBody, GLTFPhysicsShape, GLTFSkeleton, GLTFSkin, GLTFSpecGloss, GLTFState, GLTFTexture, GLTFTextureSampler, Gradient, Image, ImporterMesh, InputEvent, JointLimitation3D, JSON, LabelSettings, LightmapGIData, Material, Mesh, MeshLibrary, MissingResource, MultiMesh, NavigationMesh, NavigationMeshSourceGeometryData2D, NavigationMeshSourceGeometryData3D, NavigationPolygon, Noise, Occluder3D, OccluderPolygon2D, OggPacketSequence, OpenXRAction, OpenXRActionMap, OpenXRActionSet, OpenXRBindingModifier, OpenXRHapticBase, OpenXRInteractionProfile, OpenXRIPBinding, PackedDataContainer, PackedScene, PhysicsMaterial, PolygonPathFinder, RDShaderFile, RDShaderSPIRV, RichTextEffect, SceneReplicationConfig, Script, Shader, ShaderInclude, Shape2D, Shape3D, Shortcut, SkeletonModification2D, SkeletonModificationStack2D, SkeletonProfile, Skin, Sky, SpriteFrames, StyleBox, SyntaxHighlighter, Texture, Theme, TileMapPattern, TileSet, TileSetSource, Translation, VideoStream, VideoStreamPlayback, VisualShaderNode, VoxelGIData, World2D, World3D, X509Certificate

可序列化物件的基底類別。

說明

Resource is the base class for all Godot-specific resource types, serving primarily as data containers. Since they inherit from RefCounted, resources are reference-counted and freed when no longer in use. They can also be nested within other resources, and saved on disk. PackedScene, one of the most common Objects in a Godot project, is also a resource, uniquely capable of storing and instantiating the Nodes it contains as many times as desired.

In GDScript, resources can loaded from disk by their resource_path using @GDScript.load() or @GDScript.preload().

The engine keeps a global cache of all loaded resources, referenced by paths (see ResourceLoader.has_cached()). A resource will be cached when loaded for the first time and removed from cache once all references are released. When a resource is cached, subsequent loads using its path will return the cached reference.

Note: In C#, resources will not be freed instantly after they are no longer in use. Instead, garbage collection will run periodically and will free resources that are no longer in use. This means that unused resources will remain in memory for a while before being removed.

教學

屬性

bool

resource_local_to_scene

false

String

resource_name

""

String

resource_path

""

String

resource_scene_unique_id

方法

RID

_get_rid() virtual const

void

_reset_state() virtual

void

_set_path_cache(path: String) virtual const

void

_setup_local_to_scene() virtual

Error

copy_from_resource(resource: Resource)

Resource

duplicate(deep: bool = false) const

Resource

duplicate_deep(deep_subresources_mode: DeepDuplicateMode = 1) const

void

emit_changed()

String

generate_scene_unique_id() static

String

get_id_for_path(path: String) const

Node

get_local_scene() const

RID

get_rid() const

bool

is_built_in() const

void

reset_state()

void

set_id_for_path(path: String, id: String)

void

set_path_cache(path: String)

void

setup_local_to_scene()

void

take_over_path(path: String)


訊號

changed() 🔗

當資源發生更改時發出訊號,通常是當其屬性之一被修改時。另見 emit_changed()

注意:自訂資源的屬性不會自動發出此訊號。如有必要,需要建立一個 setter 來觸發。


setup_local_to_scene_requested() 🔗

已棄用: This signal is only emitted when the resource is created. Override _setup_local_to_scene() instead.

Emitted by a newly duplicated resource with resource_local_to_scene set to true.


列舉

enum DeepDuplicateMode: 🔗

DeepDuplicateMode DEEP_DUPLICATE_NONE = 0

No subresources at all are duplicated. This is useful even in a deep duplication to have all the arrays and dictionaries duplicated but still pointing to the original resources.

DeepDuplicateMode DEEP_DUPLICATE_INTERNAL = 1

Only subresources without a path or with a scene-local path will be duplicated.

DeepDuplicateMode DEEP_DUPLICATE_ALL = 2

Every subresource found will be duplicated, even if it has a non-local path. In other words, even potentially big resources stored separately will be duplicated.


屬性說明

bool resource_local_to_scene = false 🔗

  • void set_local_to_scene(value: bool)

  • bool is_local_to_scene()

如果為 true,那麼在本地場景的各個實例中,該資源都會被唯一化。在運作時,在某個場景中對該資源的修改不會影響其他實例(見 PackedScene.instantiate())。

注意:運作時,在已建立副本的資源上修改該屬性不會有效果。


String resource_name = "" 🔗

對於這個資源,這是一個選用的名稱。定義後,它的值會顯示以在屬性檢視器面板中表示資源。

對於內建腳本,名稱會顯示為腳本編輯器中分頁名稱的一部分。

注意: 有些資源格式不支援資源名稱。

您仍然可以在編輯器或透過程式碼設定名稱,但當資源被重新載入時,它會遺失。

例如,只有內建腳本可以有資源名稱,而儲存在獨立檔案中的腳本則不行。


String resource_path = "" 🔗

該資源的唯一路徑。如果已被保存到磁片,該值將是其檔路徑。如果該資源僅包含在某一個場景中,該值將是 PackedScene 的檔路徑後加上一個唯一識別碼。

注意:如果之前已經載入了具有相同路徑的資源,手動設定該屬性可能會失敗。如果有必要,請使用 take_over_path()


String resource_scene_unique_id 🔗

  • void set_scene_unique_id(value: String)

  • String get_scene_unique_id()

A unique identifier relative to this resource's scene. If left empty, the ID is automatically generated when this resource is saved inside a PackedScene. If the resource is not inside a scene, this property is empty by default.

Note: When the PackedScene is saved, if multiple resources in the same scene use the same ID, only the earliest resource in the scene hierarchy keeps the original ID. The other resources are assigned new IDs from generate_scene_unique_id().

Note: Setting this property does not emit the changed signal.

Warning: When setting, the ID must only consist of letters, numbers, and underscores. Otherwise, it will fail and default to a randomly generated ID.


方法說明

RID _get_rid() virtual const 🔗

可以覆蓋此方法,從而在呼叫 get_rid() 時返回自訂 RID


void _reset_state() virtual 🔗

For resources that store state in non-exported properties, such as via Object._validate_property() or Object._get_property_list(), this method must be implemented to clear them.


void _set_path_cache(path: String) virtual const 🔗

Override this method to execute additional logic after set_path_cache() is called on this object.


void _setup_local_to_scene() virtual 🔗

Override this method to customize the newly duplicated resource created from PackedScene.instantiate(), if the original's resource_local_to_scene is set to true.

Example: Set a random damage value to every local resource from an instantiated scene:

extends Resource

var damage = 0

func _setup_local_to_scene():
    damage = randi_range(10, 40)

Error copy_from_resource(resource: Resource) 🔗

Copies the data from resource into this resource. Both resources must share the same class.


Resource duplicate(deep: bool = false) const 🔗

Duplicates this resource, returning a new resource with its exported or @GlobalScope.PROPERTY_USAGE_STORAGE properties copied from the original.

If deep is false, a shallow copy is returned: nested Array, Dictionary, and Resource properties are not duplicated and are shared with the original resource.

If deep is true, a deep copy is returned: all nested arrays, dictionaries, and packed arrays are also duplicated (recursively). Any Resource found inside will only be duplicated if it's local, like DEEP_DUPLICATE_INTERNAL used with duplicate_deep().

The following exceptions apply:

Note: For custom resources, this method will fail if Object._init() has been defined with required parameters.

Note: When duplicating with deep set to true, each resource found, including the one on which this method is called, will be only duplicated once and referenced as many times as needed in the duplicate. For instance, if you are duplicating resource A that happens to have resource B referenced twice, you'll get a new resource A' referencing a new resource B' twice.


Resource duplicate_deep(deep_subresources_mode: DeepDuplicateMode = 1) const 🔗

Duplicates this resource, deeply, like duplicate() when passing true, with extra control over how subresources are handled.


void emit_changed() 🔗

發出 changed 更改訊號。內建資源會自動呼叫此方法。

注意:對於自訂資源,推薦在發生任何有意義的變化時都呼叫此方法,例如修改屬性時。這樣能夠保證依賴於此資源的自訂 Object 能夠正確更新其屬性。

var damage:
    set(new_value):
        if damage != new_value:
            damage = new_value
            emit_changed()

String generate_scene_unique_id() static 🔗

Generates a unique identifier for a resource to be contained inside a PackedScene, based on the current date, time, and a random value. The returned string is only composed of letters (a to y) and numbers (0 to 8). See also resource_scene_unique_id.


String get_id_for_path(path: String) const 🔗

From the internal cache for scene-unique IDs, returns the ID of this resource for the scene at path. If there is no entry, an empty string is returned. Useful to keep scene-unique IDs the same when implementing a VCS-friendly custom resource format by extending ResourceFormatLoader and ResourceFormatSaver.

Note: This method is only implemented when running in an editor context. At runtime, it returns an empty string.


Node get_local_scene() const 🔗

如果 resource_local_to_scenetrue,並且該資源是從 PackedScene 實例中載入的,則返回使用該資源的場景的根 Node。否則返回 null


RID get_rid() const 🔗

返回該資源的 RID(或者空的 RID)。許多資源(如 Texture2DMesh 等)是存儲在伺服器(DisplayServerRenderingServer 等)中的資源的高級抽象,所以這個函式將返回原始的 RID


bool is_built_in() const 🔗

Returns true if the resource is saved on disk as a part of another resource's file.


void reset_state() 🔗

Makes the resource clear its non-exported properties. See also _reset_state(). Useful when implementing a custom resource format by extending ResourceFormatLoader and ResourceFormatSaver.


void set_id_for_path(path: String, id: String) 🔗

In the internal cache for scene-unique IDs, sets the ID of this resource to id for the scene at path. If id is empty, the cache entry for path is cleared. Useful to keep scene-unique IDs the same when implementing a VCS-friendly custom resource format by extending ResourceFormatLoader and ResourceFormatSaver.

Note: This method is only implemented when running in an editor context.


void set_path_cache(path: String) 🔗

Sets the resource's path to path without involving the resource cache. Useful for handling CacheMode values when implementing a custom resource format by extending ResourceFormatLoader and ResourceFormatSaver.


void setup_local_to_scene() 🔗

已棄用: This method should only be called internally.

Calls _setup_local_to_scene(). If resource_local_to_scene is set to true, this method is automatically called from PackedScene.instantiate() by the newly duplicated resource within the scene instance.


void take_over_path(path: String) 🔗

resource_path 設定為 path,可能會覆蓋這個路徑對應的已有緩存條目。後續嘗試通過路徑載入覆蓋後的資源時,會返回這個資源。