Autoloads versus regular nodes¶
Godot은 프로젝트의 루트에 자동으로 노드를 로드하는 기능을 지원해 전역적으로 액세스가 가능하도록 합니다. 따라서 싱글턴 :ref:`doc_singletons_autoload`의 목적에 부합합니다. 자동으로 로드된 노드들은 코드에서 :ref:`SceneTree.change_scene <class_SceneTree_method_change_scene>`로 씬을 변경할 때 할당이 해제되지 않습니다.
이 가이드에서는 오토로드 기능을 사용할 때와 이를 피하기 위한 기법을 배우게 됩니다.
오디오 잘림 문제¶
Other engines can encourage the use of creating manager classes, singletons that organize a lot of functionality into a globally accessible object. Godot offers many ways to avoid global state thanks to the node tree and signals.
For example, let's say we are building a platformer and want to collect coins
that play a sound effect. There's a node for that: the AudioStreamPlayer. But if we call the AudioStreamPlayer
while it is
already playing a sound, the new sound interrupts the first.
A solution is to code a global, auto-loaded sound manager class. It generates a
pool of AudioStreamPlayer
nodes that cycle through as each new request for
sound effects comes in. Say we call that class Sound
, you can use it from
anywhere in your project by calling Sound.play("coin_pickup.ogg")
. This
solves the problem in the short term but causes more problems:
Global state: one object is now responsible for all objects' data. If the
Sound
class has errors or doesn't have an AudioStreamPlayer available, all the nodes calling it can break.Global access: now that any object can call
Sound.play(sound_path)
from anywhere, there's no longer an easy way to find the source of a bug.전역 리소스 할당:
AudioStreamPlayer
노드 풀을 처음에 생성하기 때문에 너무 적게 생성하면 버그가 발생하고 너무 많이 생성하면 메모리를 비효율적으로 사용하게 됩니다.
참고
전역 접근의 문제점은 어딘가의 어떤 코드든지 예제의 Sound
오토로드에 잘못된 데이터를 전달할 수 있다는 점 입니다. 결과적으로 버그를 찾기 위해 프로젝트 전체를 탐색해야 합니다.
코드를 씬 내에 국한시킬 경우, 오디오에 개입할 수 있는 스크립트는 한 두개 뿐입니다.
Contrast this with each scene keeping as many AudioStreamPlayer
nodes as it
needs within itself and all these problems go away:
각 씬은 자체적인 상태 정보를 관리합니다. 데이터에 문제가 생기면, 해당 데이터가 있는 씬 내에서만 사고를 일으킵니다.
각 씬은 자기 자신의 노드들에만 액세스합니다. 따라서 버그가 일어난다면 어느 노드에서 오류가 생긴 것인지 특정하기가 쉽습니다.
각 씬은 자신에게 정확히 필요한 양의 리소스만을 할당합니다.
언제 오토로드를 사용해야 하는지¶
다음과 같은 경우 오토로드된 노드로 코드를 간소화시킬 수 있습니다:
Static Data: 만약 데이터베이스처럼 특정한 클래스에 국한된 데이터가 필요하다면 오토로드가 유용할 수 있습니다. Godot에는 달리 정적인 데이터를 생성할 수 있는 스크립팅 API가 없습니다.
Static functions: 값만을 반환하는 함수 라이브러리를 생성합니다.
Systems with a wide scope: If the singleton is managing its own information and not invading the data of other objects, then it's a great way to create systems that handle broad-scoped tasks. For example, a quest or a dialogue system.
Godot 3.1 이전까지는 편의성을 위해 GDScript에서 생성된 오토로드의 이름에 대한 전역번수로 프로젝트의 어떤 스크립트에서든 호출이 가능했습니다. 하지만 이제 프로젝트 내 모든 타입이 자동완성되는 걸 보고 있을 필요 없이 class_name
키워드를 사용하면 됩니다.
참고
오토로드는 정확히 말하자면 싱글턴은 아닙니다. 오토로드된 노드의 복사본을 인스턴스화 하는데 아무런 제약이 없기 때문입니다. 오토로드는 그저 노드가 게임의 노드 구조나 :kbd:`F6`키를 누르면 어떤 씬이 실행되는지 여부에 관계 없이 자동으로 씬 트리의 자식 노드로 만들어주는 도구일 뿐입니다.
결과적으로 만약 오토로드의 이름이 Sound
라면 get_node("/root/Sound")
를 호출해서 오토로드된 노드를 얻을 수 있습니다.