> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-ko/sdk7/networking/serverless-multiplayer.md).

# 서버리스 멀티플레이어

플레이어 간에 씬 상태를 동기화합니다.

Decentraland는 각 플레이어의 익스플로러 인스턴스에서 씬을 로컬로 실행합니다. 기본적으로 플레이어는 서로를 보고 직접 상호작용할 수 있지만, 각 플레이어는 환경과 독립적으로 상호작용합니다. 환경의 변경 사항은 기본적으로 플레이어 간에 공유되지 않습니다.

플레이어가 더 의미 있게 상호작용하려면 동일한 콘텐츠를 동일한 상태로 보는 것이 매우 중요합니다.

모든 플레이어에게 같은 화면이 보이도록 씬 상태를 동기화하는 방법은 세 가지입니다.

* **엔티티를 동기화 대상으로 표시**: 가장 쉬운 방법입니다. 자세한 내용: [엔티티를 동기화 대상으로 표시](#mark-an-entity-as-synced)
* **명시적인 MessageBus 메시지 전송**: 특정 메시지를 수동으로 전송하고 수신합니다. 자세한 내용: [명시적인 MessageBus 메시지 전송](#send-explicit-messagebus-messages)
* **멀티플레이어 서버 사용**: 자세한 내용: [멀티플레이어 서버](/creator/content-creator-ko/sdk7/networking/authoritative-servers.md). 서버가 모든 상태 변경을 검증하며 유일한 정보원이 됩니다. 추가 설정이 필요하지만 플레이어가 씬의 허점을 악용할 유인이 있는 경우에는 이 방법을 적극 권장합니다.

이 문서에서는 앞의 두 가지 방법을 다룹니다. 두 방법은 서버가 필요하지 않아 더 간단합니다. 단점은 플레이어의 연결 속도에 더 많이 의존하며, 모든 플레이어가 씬을 떠나면 씬 상태가 유지되지 않는다는 것입니다.

## 엔티티를 동기화 대상으로 표시

엔티티를 동기화 대상으로 표시하려면 [Creator Hub](/creator/content-creator-ko/scene-editor/get-started/about-editor.md)에서 해당 엔티티에 **멀티플레이어 컴포넌트** 를 추가하세요. 이 컴포넌트에는 엔티티의 다른 각 컴포넌트에 대한 체크박스가 있어 업데이트할 컴포넌트를 선택할 수 있습니다.

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-3c4e9da9a4f012190b0cfd80e26ad80580ab9ba7%2Fmultiplayer-component.webp?alt=media)

코드에서 엔티티를 동기화 대상으로 표시하려면 `syncEntity` 함수를 사용하세요.

```ts
import { syncEntity } from "@dcl/sdk/network";

export function main() {
  const doorEntity = engine.addEntity();

  syncEntity(doorEntity, [Transform.componentId, Animator.componentId], 1);
}
```

{% hint style="warning" %}
**📔 참고**: 항상 `syncEntity()` 를 `main()` 함수 안이나 `main()` 이후에 실행되는 함수(예: 콜백 또는 시스템) 안에서 호출하세요. 파일의 최상위 수준에서 호출하면 해당 시점에는 플레이어 프로필이 아직 초기화되지 않아 오류가 발생합니다.
{% endhint %}

{% hint style="warning" %}
**📔 참고**: 서버리스 멀티플레이어에서는 모든 클라이언트가 각자 `syncEntity` 를 호출합니다. [멀티플레이어 서버](/creator/content-creator-ko/sdk7/networking/authoritative-servers.md)로 업그레이드하면 패턴이 달라집니다. 서버만 `syncEntity`를 호출해야 하며, 호출 여부를 `isServer()`로 확인해야 합니다. 클라이언트는 자신이 생성한 엔티티가 아니라면 공유 엔티티의 동기화를 선언하지 않아야 합니다.
{% endhint %}

다음은 `syncEntity` 함수에 전달하는 입력값입니다.

* **entityId**: 동기화할 엔티티에 대한 참조
* **componentIds**: 해당 엔티티에서 동기화해야 하는 컴포넌트의 목록입니다. 필요한 만큼의 컴포넌트를 포함할 수 있는 배열입니다. 모든 값은 `componentId` 속성입니다.
* **entityEnumId**: (선택 사항) 모든 플레이어가 일관되게 사용하는 고유 ID입니다. 자세한 내용은 [enum ID 소개](#about-the-enum-id).

모든 엔티티나 컴포넌트를 동기화해야 하는 것은 아닙니다. 같은 위치에 계속 있는 나무와 같은 정적 요소는 동기화할 필요가 없습니다. 동기화하는 엔티티에서도 시간이 지남에 따라 변경되는 컴포넌트만 동기화해야 합니다. 예를 들어 큐브를 클릭했을 때 색이 바뀐다면 Material 컴포넌트만 동기화하면 됩니다. MeshRenderer나 Transform은 변경되지 않으므로 동기화할 필요가 없습니다.

{% hint style="info" %}
**💡 팁**: 공유하려는 데이터가 컴포넌트로 존재하지 않는다면, 해당 데이터를 담는 [사용자 지정 컴포넌트](/creator/content-creator-ko/sdk7/architecture/custom-components.md) 를 정의하세요.
{% endhint %}

### enum ID 소개

엔티티의 **entityEnumId** 는 고유해야 합니다. 이는 `engine.addEntity()`에서 할당되는 로컬 entityId와는 관련이 없습니다. 로컬 entityId는 자동 생성되며, 같은 씬을 실행하는 플레이어마다 다를 수 있습니다. 엔티티의 entityEnumId는 코드에서 명시적으로 정의해야 하며 고유해야 합니다.

경쟁 상태로 인해 씬의 한 부분이 다른 부분보다 먼저 로드될 경우 불일치가 발생할 수 있으므로, 이 ID를 명시적으로 설정하는 것이 중요합니다. 플레이어 A에게 씬의 문은 엔티티 *512*일 수 있지만, 플레이어 B에게는 같은 문이 엔티티 *513*일 수 있습니다. 이 경우 플레이어 A가 문을 열면 플레이어 B에게는 문 대신 건물 전체가 움직이는 것으로 보입니다.

{% hint style="info" %}
**💡 팁**: 씬에서 동기화할 수 있는 각 ID를 명확히 참조할 수 있도록 enum을 만드세요.

```ts
import { syncEntity } from "@dcl/sdk/network";

enum EntityEnumId {
  DOOR = 1,
  DRAW_BRIDGE = 2,
  ELEVATOR = 3,
}

export function main() {
  syncEntity(
    doorEntity,
    [Transform.componentId, Animator.componentId],
    EntityEnumId.DOOR
  );
}
```

여기서는 EntityEnumId enum을 사용해 엔티티에 고유 식별자를 부여합니다. 따라서 생성 순서와 관계없이 모든 클라이언트가 수정된 엔티티를 인식할 수 있습니다.
{% endhint %}

{% hint style="warning" %}
**📔 참고**: 씬에 Smart Item도 포함되어 있다면 다음보다 큰 숫자는 사용하지 마세요. **8001** Creator Hub에서 생성된 항목에는 Multiplayer 컴포넌트가 있을 경우 8001부터 자동 할당된 ID가 사용됩니다. 8001보다 작은 ID는 동기화할 엔티티에 안전하게 할당할 수 있습니다. [Creator Hub](/creator/content-creator-ko/scene-editor/get-started/about-editor.md) 에서 Multiplayer 컴포넌트와 함께 생성된 항목에는 8001부터 자동 할당된 ID가 사용됩니다. 8001보다 작은 ID는 동기화할 엔티티에 안전하게 할당할 수 있습니다.
{% endhint %}

**플레이어가 생성하는 엔티티**

플레이어의 상호작용으로 엔티티가 생성되고 이 엔티티를 다른 플레이어와 동기화해야 한다면, entityEnumId는 필요하지 않습니다. 엔티티와 컴포넌트 목록만 전달하여 `syncEntity()` 를 사용할 수 있습니다. entityEnumId의 고유 값은 내부적으로 자동 할당됩니다.

씬이 시작될 때 인스턴스화되는 모든 엔티티에는 ID를 수동으로 할당해야 합니다. 모든 플레이어가 각 엔티티에 동일한 ID를 사용하도록 하기 위해서입니다. 한 플레이어가 엔티티 인스턴스화를 담당하는 경우에는 ID를 명시적으로 지정할 필요가 없습니다. 다른 플레이어는 ID가 이미 할당된 새 엔티티에 대한 업데이트를 받으므로 ID가 일치하지 않을 위험이 없습니다.

예를 들어 눈싸움 씬에서 플레이어가 눈덩이를 던질 때마다 새 엔티티가 인스턴스화되어 다른 플레이어와 동기화됩니다. 눈덩이에는 고유한 entityEnumId가 필요하지 않습니다.

```ts
import { syncEntity } from "@dcl/sdk/network";

function onThrow() {
  const ball = engine.addEntity();
  Transform.create(ball, {});
  GltfContainer.create(ball, { src: "assets/snowBall.glb" });
  syncEntity(ball, [Transform.componentId, GltfContainer.componentId]);
}
```

### 부모가 지정된 엔티티 <a href="#parented-entities" id="parented-entities"></a>

엔티티의 부모는 일반적으로 `parent` 속성을 통해 `Transform` 컴포넌트입니다. 하지만 이 속성은 부모의 로컬 엔터티 ID를 가리키며, 이 ID는 달라질 수 있습니다. 다음을 참고하세요:  [열거형 ID 정보](#about-the-enum-id). 동기화해야 하는 엔터티나 동기화해야 하는 자식이 있는 엔터티의 부모를 지정하려면  `parentEntity()`  함수를 다음 항목 대신 사용하세요:  `Transform`.

```ts
import { syncEntity, parentEntity } from "@dcl/sdk/network";

export function main() {
  const parent = engine.addEntity();
  Transform.create(parent, { position: somePosition });
  syncEntity(parent, []);

  const child: Entity = engine.addEntity();
  syncEntity(child, [Transform.componentId]);

  parentEntity(child, parent);
}
```

부모와 자식 모두  `syncEntity`로 동기화되므로 모든 플레이어가 두 엔터티에 사용되는 ID를 동일하게 인식합니다. 부모의 컴포넌트를 변경할 필요가 없는 경우에도 이렇게 해야 합니다. 이 예제에서는  `syncEntity` 에 빈 컴포넌트 배열을 전달하여 불필요한 컴포넌트가 동기화되지 않도록 합니다.

{% hint style="warning" %}
**📔 참고**: 엔터티의 부모가  `parentEntity()` 와  `parent`  속성으로 모두 지정되어 있고 그 속성이  `Transform`  컴포넌트에 있다면,  `Transform`  컴포넌트의 속성은 무시됩니다.
{% endhint %}

엔터티의 부모가  `parentEntity()`  함수로 지정된 경우 다음 헬퍼 함수도 사용할 수 있습니다:

* **removeParent()**:  `parentEntity()`의 효과를 되돌립니다. 자식 엔터티만 전달해야 합니다. 엔터티의 새 부모는 씬의 루트 엔터티가 됩니다. 기존 부모 엔터티는 씬에서 제거되지 않습니다.
* **getParent()**: 전달한 엔터티의 부모 엔터티를 반환합니다.
* **getChildren()**: 전달한 엔터티의 자식 목록을 순회 가능한 객체로 반환합니다.
* **getFirstChild()**: 전달한 엔터티의 자식 목록에서 첫 번째 자식을 반환합니다.

```ts
import {
  syncEntity,
  parentEntity,
  getParent,
  getFirstChild,
  getChildren,
  removeParent,
} from "@dcl/sdk/network";

export function main() {
  const parent = engine.addEntity();
  Transform.create(parent, { position: somePosition });
  syncEntity(parent, []);

  const child: Entity = engine.addEntity();
  syncEntity(child, [Transform.componentId]);

  // parent를 부모로 설정합니다
  parentEntity(child, parent);

  // getParent
  const getParentResult = getParent(child);
  // parent를 반환합니다

  // getFirstChild
  const getFirstChildResult = getFirstChild(parent);
  // child를 반환합니다

  // getChildren
  const getChildrenResult = Array.from(getChildren(parent));
  // [child]를 반환합니다

  // child에서 parent를 제거합니다
  removeParent(child);
}
```

## 동기화 상태 확인

플레이어가 씬에 막 진입한 경우 주변의 다른 플레이어와 아직 동기화되지 않았을 수 있습니다. 플레이어가 동기화되기 전에 게임 상태를 변경하기 시작하면 게임에 문제가 생길 수 있습니다. 플레이어가 씬의 어떤 항목이든 수정할 수 있도록 허용하기 전에 항상 동기화 여부를 확인하는 것이 좋습니다.

플레이어가 씬의 파셀 밖으로 나가면 밖에 있는 동안 씬과의 동기화도 해제됩니다. 플레이어가 근처에 있는 동안에는 씬이 계속 실행되므로 씬의 시스템이 이러한 상황을 처리하는 것도 중요합니다. 플레이어가 다시 안으로 들어오면 씬 상태의 변경 사항이 자동으로 플레이어에게 반영됩니다.

플레이어의 씬 상태가 현재 동기화되어 있는지 확인하려면 `isStateSyncronized()` 함수를 사용하세요. 이 함수는 불리언을 반환하며, 플레이어가 이미 씬과 동기화되어 있으면 true입니다.

```ts
import { isStateSyncronized } from "@dcl/sdk/network";

const isConnected = isStateSyncronized();
```

예를 들어 시스템에 이 확인 절차를 포함하고, 이 함수가 false를 반환하면 모든 상호작용을 차단할 수 있습니다.

```ts
import { isStateSyncronized } from "@dcl/sdk/network";

engine.addSystem(() => {
  if (isStateSyncronized() && !button.enabled) {
    console.log("Enable Start Game");
    button.enable();
  }

  if (!isStateSyncronized() && button.enabled) {
    console.log(`Disable Start Game.`);
    button.disable();
  }
});
```

## 명시적 MessageBus 메시지 보내기

{% hint style="warning" %}
**📔 참고**: `MessageBus` API는 SDK에서 더 이상 사용되지 않는 것으로 표시되어 있으며, 향후 버전에서 제거될 수 있습니다. 대부분의 경우 [엔티티를 동기화 대상으로 표시하는 방법을 사용하세요](#mark-an-entity-as-synced).
{% endhint %}

**메시지 버스 초기화**

플레이어 간에 메시지를 주고받는 데 필요한 메서드를 처리할 메시지 버스 객체를 생성합니다.

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();
```

**메시지 보내기**

메시지 버스의 `.emit` 명령을 사용하여 씬에 있는 다른 모든 플레이어에게 메시지를 보냅니다.

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();

const myEntity = engine.addEntity();
MeshRenderer.setBox(myEntity);
MeshCollider.setBox(myEntity);

pointerEventsSystem.onPointerDown(
  {
    entity: myEntity,
    opts: { button: InputAction.IA_PRIMARY, hoverText: "Click" },
  },
  function () {
    sceneMessageBus.emit("box1Clicked", {});
  }
);
```

각 메시지에는 두 번째 인수로 페이로드를 포함할 수 있습니다. 페이로드의 타입은 `Object`이며, 전송하려는 관련 데이터를 자유롭게 포함할 수 있습니다.

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();

sceneMessageBus.emit("spawn", { position: { x: 10, y: 2, z: 10 } });
```

{% hint style="info" %}
**💡 팁**: 하나의 메시지에 여러 변수의 데이터를 포함해야 한다면, 이 모든 데이터를 하나의 객체에 담을 수 있도록 사용자 정의 타입을 만드세요.
{% endhint %}

**메시지 받기**

해당 씬에 있는 다른 모든 플레이어의 메시지를 처리하려면 다음을 사용하세요: `.on`. 이 함수를 사용할 때는 메시지 문자열을 제공하고 실행할 함수를 정의합니다. 일치하는 문자열의 메시지가 도착할 때마다 지정된 함수가 한 번 실행됩니다.

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();

type NewBoxPosition = {
  position: { x: number; y: number; z: number };
};

sceneMessageBus.on("spawn", (info: NewBoxPosition) => {
  const myEntity = engine.addEntity();
  Transform.create(myEntity, {
    position: { x: info.position.x, y: info.position.y, z: info.position.z },
  });
  MeshRenderer.setBox(myEntity);
  MeshCollider.setBox(myEntity);
});
```

{% hint style="warning" %}
**📔 참고**: 플레이어가 보낸 메시지는 해당 플레이어 자신에게도 전달됩니다.  `.on`  메서드는 해당 플레이어가 보낸 메시지와 다른 플레이어가 보낸 메시지를 구분할 수 없습니다.
{% endhint %}

**MessageBus 전체 예제**

이 예제에서는 메시지 버스를 사용해 메인 큐브를 클릭할 때마다 새 메시지를 보내고, 무작위 위치에 새 큐브를 생성합니다. 새 큐브의 위치가 메시지에 포함되므로 모든 플레이어가 같은 위치에 큐브를 볼 수 있습니다.

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

/// --- 메시지 버스 생성 ---
const sceneMessageBus = new MessageBus();

// 큐브 생성 함수
function createCube(x: number, y: number, z: number): Entity {
  const meshEntity = engine.addEntity();
  Transform.create(meshEntity, { position: { x, y, z } });
  MeshRenderer.setBox(meshEntity);
  MeshCollider.setBox(meshEntity);

  // 큐브를 클릭하면 메시지를 보내 다른 큐브를 생성
  pointerEventsSystem.onPointerDown(
    {
      entity: meshEntity,
      opts: { button: InputAction.IA_PRIMARY, hoverText: "E 키를 눌러 생성" },
    },
    function () {
      sceneMessageBus.emit("spawn", {
        position: {
          x: 1 + Math.random() * 8,
          y: Math.random() * 8,
          z: 1 + Math.random() * 8,
        },
      });
    }
  );

  return meshEntity;
}

// 초기화
createCube(8, 1, 8);

// 데이터 유형 정의
type NewBoxPosition = {
  position: { x: number; y: number; z: number };
};

// spawn 메시지를 받으면 새 큐브 생성
sceneMessageBus.on("spawn", (info: NewBoxPosition) => {
  createCube(info.position.x, info.position.y, info.position.z);
});
```

## 멀티플레이어 씬을 로컬에서 테스트하기

씬 미리보기를 실행하고 서로 다른 탐색기 창 두 개 이상에서 열면, 열린 각 창이 별도의 플레이어로 인식되고 모의 통신 서버가 플레이어 간 동기화를 유지합니다.

한 창에서 씬과 상호작용한 다음 다른 창으로 전환해 상호작용의 효과가 그곳에도 표시되는지 확인하세요.

Creator Hub에서 **다중 인스턴스 미리 보기** 을 **데스크톱 클라이언트** 의 하위 메뉴 **재생 옵션**, 그런 다음 **재생**  버튼을 한 번 더 클릭하면 Decentraland 탐색기 창이 하나 더 열립니다. 두 창 모두 서로 다른 주소로 연결해야 합니다. 장면이 다시 로드되어도 두 세션은 열린 상태로 유지됩니다.

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-10d53f215e20e8cf603bbf578d0b33df738d058f%2Fpreview-button.webp?alt=media)

또는 브라우저 주소창에 다음을 입력해 Decentraland 탐색기 창을 하나 더 열 수 있습니다.

> `decentraland://realm=http://127.0.0.1:8000&local-scene=true&debug=true&multi-instance=true`

## 싱글 플레이어 씬

씬을  [Decentraland World](/creator/content-creator-ko/sdk7/publishing/publishing-options.md#decentraland-worlds)에 배포하는 경우 싱글 플레이어 씬으로 설정할 수 있습니다. 플레이어들은 서로를 볼 수 없고, 채팅하거나 서로의 행동이 미치는 영향을 볼 수도 없습니다.

이렇게 하려면 씬의  `scene.json`  파일에서  **fixedAdapter** 를  `offline:offline`로 설정합니다. 씬에는 Communication Service가 전혀 연결되지 않으며, 해당 월드에 입장하는 사용자는 항상 혼자 있게 됩니다.

**예:**

```json
{
  "worldConfiguration": {
    "name": "my-name.dcl.eth",
    "fixedAdapter": "offline:offline"
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-ko/sdk7/networking/serverless-multiplayer.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
