> For the complete documentation index, see [llms.txt](/llms.txt)

# Game Engine

GS2-SDK for Game Engine의 초기화 방법에 대해



## SDK 초기화

GS2 이용을 시작하려면 먼저 GS2-SDK의 초기화 처리를 수행합니다.
`Gs2Client.Create`를 호출함으로써 GS2의 클라이언트 인스턴스인 `Gs2Domain`을 얻을 수 있습니다.

초기화에 필요한 파라미터는 다음과 같습니다.

### 파라미터

| 인자명                      | 타입                   | 설명           |
|--------------------------|---------------------|--------------|
| credential               | BasicGs2Credential  | 크리덴셜 정보    |
| region                   | Region | 접속 대상 GS2 리전 |

#### BasicGs2Credential

"클라이언트ID"와 "클라이언트시크릿"을 지정합니다.
이 값들은 GS2-Identifier에서 관리하고 있습니다.

#### Region

GS2의 데이터센터를 지정합니다.
지정 가능한 값에 대해서는 [리전]()을 참조해 주십시오.

### 구현 예제



**Unity (UniTask)**
```csharp

    var gs2 = await Gs2.Unity.Core.Gs2Client.CreateAsync(
        new Gs2.Core.Model.BasicGs2Credential(
            "your client id",
            "your client secret"
        ),
        Gs2.Core.Model.Region.ApNortheast1
    );
```
**Unity (Vanilla)**
```cs

    var future = Gs2.Unity.Core.Gs2Client.CreateFuture(
        new Gs2.Core.Model.BasicGs2Credential(
            "your client id",
            "your client secret"
        ),
        Gs2.Core.Model.Region.ApNortheast1
    );
    yield return future;
    if (future.Error != null) {
        throw future.Error;
    }
    var gs2 = future.Result;
```
**Unreal Engine 5**
```cpp

    const auto future = Gs2::UE5::Core::FGs2Client::Create(
        MakeShared<Gs2::Core::Model::FBasicGs2Credential>(
            "your client id",
            "your client secret"
        ),
        Gs2::Core::Model::ApNorthEast1
    );
    future->StartSynchronousTask();
    if (future->GetTask().IsError())
    {
        UE_LOG(GameLog, Error, TEXT("%s"), ToCStr(future->GetTask().Error()->String()));
        return future->GetTask().Error();
    }
    const auto Gs2 = future->GetTask().Result();
```


#### 카오스 모드

카오스 모드를 적용한 SDK 초기화 처리를 호출함으로써 API 요청을 일정한 확률로 실패시킬 수 있습니다.
카오스 모드를 활성화한 클라이언트를 사용하여 개발을 진행함으로써 에러 핸들링을 더욱 견고하게 만들 수 있습니다.



**Unity (UniTask)**
```csharp

    var gs2 = await Gs2.Unity.Core.Gs2Client.CreateChaosAsync(
        new Gs2.Core.Model.BasicGs2Credential(
            "your client id",
            "your client secret"
        ),
        0.1f, // API 요청 시 10%의 확률로 재시도가 필요한 에러를 발생시킴
        Gs2.Core.Model.Region.ApNortheast1
    );
```
**Unity (Vanilla)**
```cs

    var future = Gs2.Unity.Core.Gs2Client.CreateChaosFuture(
        new Gs2.Core.Model.BasicGs2Credential(
            "your client id",
            "your client secret"
        ),
        0.1f, // API 요청 시 10%의 확률로 재시도가 필요한 에러를 발생시킴
        Gs2.Core.Model.Region.ApNortheast1
    );
    yield return future;
    if (future.Error != null) {
        throw future.Error;
    }
    var gs2 = future.Result;
```
**Unreal Engine 5**
```cpp

    const auto future = Gs2::UE5::Core::FGs2Client::CreateChaos(
        MakeShared<Gs2::Core::Model::FBasicGs2Credential>(
            "your client id",
            "your client secret"
        ),
        0.1f, // API 요청 시 10%의 확률로 재시도가 필요한 에러를 발생시킴
        Gs2::Core::Model::ApNorthEast1
    );
    future->StartSynchronousTask();
    if (future->GetTask().IsError())
    {
        UE_LOG(GameLog, Error, TEXT("%s"), ToCStr(future->GetTask().Error()->String()));
        return future->GetTask().Error();
    }
    const auto Gs2 = future->GetTask().Result();
```


## 계정 생성

GS2의 많은 기능은 플레이어의 GS2-Account 계정 정보를 지정하여 로그인해야 합니다.
로그인을 하려면 계정 생성이 필요합니다.

계정을 생성하려면 `Gs2Domain::Account::Namespace()::Create`를 사용합니다.

### 파라미터

| 인자명           | 타입  | 설명                    |
|---------------|----|-----------------------|
| namespaceName | string | GS2-Account의 네임스페이스명 |

### 구현 예제



**Unity (UniTask)**
```csharp

    var account = await (
        await gs2.Account.Namespace(
            this.accountNamespaceName
        ).CreateAsync()
    ).ModelAsync();

    var userId = account.UserId;
    var password = account.Password;
```
**Unity (Vanilla)**
```cs

    var future = gs2.Account.Namespace(
        this.accountNamespaceName
    ).CreateFuture();
    yield return future;
    if (future.Error != null) {
        throw future.Error;
    }
    var future2 = future.Result.ModelFuture();
    yield return future2;
    if (future2.Error != null) {
        throw future2.Error;
    }
    var account = future2.Result;

    var userId = account.UserId;
    var password = account.Password;
```
**Unreal Engine 5**
```cpp

    const auto CreateFuture = Gs2->Account->Namespace(
        AccountNamespaceName
    )->Create();
    CreateFuture->StartSynchronousTask();
    if (CreateFuture->GetTask().IsError())
    {
        UE_LOG(GameLog, Error, TEXT("%s"), ToCStr(CreateFuture->GetTask().Error()->String()));
        return CreateFuture->GetTask().Error();
    }

    const auto LoadFuture = CreateFuture->GetTask().Result()->Model();
    LoadFuture->StartSynchronousTask();
    if (LoadFuture->GetTask().IsError())
    {
        UE_LOG(GameLog, Error, TEXT("%s"), ToCStr(LoadFuture->GetTask().Error()->String()));
        return LoadFuture->GetTask().Error();
    }
    const auto Account = LoadFuture->GetTask().Result();

    auto UserId = Account->GetUserId();
    auto Password = Account->GetPassword();
```


## 로그인

SDK 초기화와 계정 생성이 끝나면 로그인할 준비가 완료됩니다.
`Gs2Domain::Login`을 사용함으로써 로그인을 실행할 수 있습니다.

결과적으로 GameSession 객체를 얻을 수 있습니다.
많은 API는 GameSession을 전달해야 하며, 이를 통해 로그인 중인 플레이어의 사용자 데이터에 접근할 수 있습니다.

### 파라미터

| 인자명           | 타입              | 설명                       |
|---------------|----------------|--------------------------|
| authenticator | IAuthenticator | 인증 처리에 사용하는 구현(GS2-Account) |
| userId        | string         | 사용자ID                   |
| password      | string         | 비밀번호                    |

#### IAuthenticator

인증 처리는 인터페이스로 정의되어 있어, GS2-Account를 사용하지 않고 자사의 인증 기반으로 인증을 대체하는 구현도 가능합니다.

#### Gs2AccountAuthenticator

Gs2AccountAuthenticator는 일반적인 사용 사례에서 충분한 기능을 갖춘, GS2-Account를 이용한 인증 구현입니다.

| 인자명            | 타입              | 설명                            |
|----------------|----------------|-------------------------------|
| accountSetting | AccountSetting | GS2-Account로 인증하기 위한 정보        |
| gatewaySetting | GatewaySetting | GS2-Gateway로 알림을 받기 위한 정보     |
| versionSetting | VersionSetting | GS2-Version으로 버전 체크를 하기 위한 정보 |

#### AccountSetting

| 인자명                  | 타입              | 설명                                             |
|----------------------|----------------|------------------------------------------------|
| accountNamespaceName | string         | GS2-Account의 네임스페이스명                          |
| keyId                | string | 인증 처리에 사용하는 GS2-Key의 암호화 키ID(생략하면 기본 암호화 키가 사용됩니다) |

#### GatewaySetting

| 인자명                  | 타입      | 설명                                              |
|----------------------|--------|-------------------------------------------------|
| gatewayNamespaceName | string | GS2-Gateway의 네임스페이스명(생략하면 기본 네임스페이스가 사용됩니다) |
| allowConcurrentAccess                | bool     | 동일한 사용자ID로의 다중 로그인을 허용할지 여부(기본값: true)              |

#### VersionSetting

VersionSetting을 적용함으로써 로그인 시나 세션 재접속 시에 자동으로 GS2-Version을 사용한 버전 체크를 수행하도록 할 수 있습니다.
버전 체크 결과 에러가 발생하면 `Gs2AccountAuthenticator::onDetectVersionUp`에 등록한 이벤트 핸들러가 호출됩니다.

| 인자명                  | 타입      | 설명                                         |
|----------------------|--------|--------------------------------------------|
| versionNamespaceName | string | GS2-Version의 네임스페이스명(생략하면 버전 체크를 하지 않습니다) |
| targetVersions                | EzTargetVersion[]     | 게임의 버전 정보                                |

### 구현 예제



**Unity (UniTask)**
```csharp

    var gameSession = await gs2.LoginAsync(
        new Gs2AccountAuthenticator(
            accountSetting: new AccountSetting {
                accountNamespaceName = this.accountNamespaceName,
            }
        ),
        account.UserId,
        account.Password
    );
```
**Unity (Vanilla)**
```cs

    var future = gs2.LoginFuture(
        new Gs2AccountAuthenticator(
            accountSetting: new AccountSetting {
                accountNamespaceName = this.accountNamespaceName,
            }
        ),
        account.UserId,
        account.Password
    );
    yield return future;
    if (future.Error != null) {
        throw future.Error;
    }
    var gameSession = future.Result;
```
**Unreal Engine 5**
```cpp

    const auto LoginFuture = Gs2->Login(
        MakeShareable<Gs2::UE5::Util::IAuthenticator>(
            new Gs2::UE5::Util::FGs2AccountAuthenticator(
                MakeShared<Gs2::UE5::Util::FAccountSetting>(
                    AccountNamespaceName
                )
            )
        ),
        *Account->GetUserId(),
        *Account->GetPassword()
    );
    LoginFuture->StartSynchronousTask();
    if (LoginFuture->GetTask().IsError())
    {
        UE_LOG(GameLog, Error, TEXT("%s"), ToCStr(LoginFuture->GetTask().Error()->String()));
        return LoginFuture->GetTask().Error();
    }
    const auto GameSession = LoginFuture->GetTask().Result();
```





