기술 자료

지원

Cloud Code

Cloud Code

Unity Runtime에서 호출

Invoke scripts from an authenticated game client in the Unity Editor.
읽는 시간 2분최근 업데이트: 12시간 전

Unity 에디터에서 인증된 게임 클라이언트로부터 스크립트를 호출하여 실행합니다.

필수 조건

Unity 에디터에서 Cloud Code를 사용하려면 먼저 Cloud Code SDK를 설치하고 Unity Gaming Services 프로젝트를 Unity 에디터에 연결해야 합니다.

프로젝트 연결

Unity Gaming Services 프로젝트를 Unity 에디터와 연결합니다. Unity Cloud Dashboard에서 UGS 프로젝트 ID를 확인할 수 있습니다.
  1. Unity 에디터에서 Edit > Project Settings > Services를 선택합니다.
  2. 프로젝트를 연결합니다.
    • 프로젝트에 Unity 프로젝트 ID가 없는 경우 다음 단계를 진행합니다.
      1. Create a Unity Project ID > Organizations를 선택한 다음 드롭다운 메뉴에서 조직을 선택합니다.
      2. Create project ID를 선택합니다.
    • Unity 프로젝트 ID가 있는 경우 다음 단계를 진행합니다.
      1. Use an existing Unity project ID를 선택합니다.
      2. 드롭다운 메뉴에서 조직과 프로젝트를 선택합니다.
      3. Link project ID를 선택합니다.
Unity 프로젝트 ID가 표시되고 이제 Unity 서비스에 프로젝트가 연결됩니다.
UnityEditor.CloudProjectSettings.projectId
를 사용하여 Unity 에디터 스크립트에서 프로젝트 ID에 액세스할 수도 있습니다.

SDK 설치

다음 단계를 따라 Unity 에디터용 최신 Cloud Code 패키지를 설치합니다.
  1. Unity 에디터에서 Window > Package Manager를 엽니다.
  2. Package Manager에서 Unity Registry 목록 뷰를 선택합니다.
  3. com.unity.services.cloudcode
    를 검색하거나 목록에서 Cloud Code 패키지를 찾습니다.
  4. 패키지를 선택하고 Install을 클릭합니다.

SDK 설정

Cloud Code SDK는 퍼블리시된 스크립트만 호출할 수 있습니다. 스크립트를 작성하고 퍼블리시하는 방법에 대한 자세한 내용은 스크립트 작성을 참고하십시오. 다음 단계를 따라 Cloud Code SDK를 시작합니다.
  1. Unity Cloud Dashboard 페이지의 Cloud Code 페이지를 통해 서비스를 활성화합니다.
  2. Cloud Code와 Authentication SDK를 모두 설치합니다.
  3. Edit > Project Settings... > Services를 선택하여 Unity 에디터 내에서 클라우드 프로젝트에 로그인합니다.
  4. Unity 에디터에서 새 C# Monobehaviour 스크립트를 생성합니다. Unity 매뉴얼의 스크립트 생성 및 사용을 참고하십시오.
  5. 스크립트에서 await
    UnityServices.InitializeAsync()
    를 사용하여 Core SDK를 초기화합니다.
  6. 스크립트에서 Authentication SDK를 초기화합니다.

일반적인 워크플로

Unity 에디터의 일반 MonoBehaviour C# 스크립트에서 Cloud Code SDK를 호출할 수 있습니다.
  1. Unity 엔진 내에서 C#
    MonoBehaviour
    스크립트를 생성합니다. Unity - 매뉴얼: 스크립트 생성 및 사용을 참고하십시오.
  2. MonoBehaviour
    스크립트 내에서 Unity Authentication 서비스를 구성합니다.
  3. MonoBehaviour
    스크립트 내에서 Cloud Code SDK에 호출을 추가합니다.
  4. 게임 오브젝트에
    MonoBehaviour
    스크립트를 연결합니다. 에디터 스크립팅을 참고하십시오.
  5. 플레이 버튼을 선택하고 프로젝트를 실행하여 Cloud Code가 작동하는지 확인합니다.

Authentication

Cloud Code 서비스에 액세스하려면 플레이어에게 유효한 플레이어 ID와 액세스 토큰이 있어야 합니다. Cloud Code API를 사용하려면 먼저 Authentication SDK로 플레이어를 인증해야 합니다. C# Monobehaviour 스크립트 내에서 Authentication SDK를 초기화하여 인증할 수 있습니다. [플레이어 인증](../authentication.mdx#authenticate players)을 참고하십시오. Authentication SDK를 초기화하려면 C# Monobehaviour 스크립트에 다음을 추가합니다. C#
await AuthenticationService.Instance.SignInAnonymouslyAsync();
익명 인증을 사용하여 시작하는 것이 좋습니다. 다음은 Authentication 패키지를 사용하여 익명 인증을 시작하고 Unity 에디터 내의 스크립트에서 플레이어 ID를 기록하는 방법을 보여 주는 예시입니다. C#
using Unity.Services.Authentication;using System.Threading.Tasks;using Unity.Services.Core;using UnityEngine;public class AuthenticationExample : MonoBehaviour{ internal async Task Awake() { await UnityServices.InitializeAsync(); await SignInAnonymously(); } private async Task SignInAnonymously() { AuthenticationService.Instance.SignedIn += () => { var playerId = AuthenticationService.Instance.PlayerId; Debug.Log("Signed in as: " + playerId); }; AuthenticationService.Instance.SignInFailed += s => { // Take some action here... Debug.Log(s); }; await AuthenticationService.Instance.SignInAnonymouslyAsync(); }}

Cloud Code 스크립트 호출

새로 생성한 스크립트에 인증을 포함하고 나면 Cloud Code 스크립트를 호출할 수 있습니다. 다음 네임스페이스를 포함해서 Cloud Code를 Unity 에디터 프로젝트와 연동합니다. C#
Using Unity.Services.CloudCode;
생성한 스크립트를 실행하려면
CloudCodeService.Instance
에 있는
CallEndpointAsync
API 클라이언트 메서드를 사용합니다.
C#
/// <summary>/// Calls a Cloud Code function./// </summary>/// <param name="function">Cloud Code function to call.</param>/// <param name="args">Arguments for the cloud code function. Will be serialized to JSON.</param>/// <typeparam name="TResult">Serialized from JSON returned by Cloud Code.</typeparam>/// <returns>Serialized output from the called function.</returns>/// <exception cref="CloudCodeException">Thrown if request is unsuccessful.</exception>/// <exception cref="CloudCodeRateLimitedException">Thrown if the service returned rate limited error.</exception>public async Task<TResult> CallEndpointAsync<TResult>(string function, Dictionary<string, object> args)
function
파라미터는 스크립트 이름입니다. Unity Cloud Dashboard에서 스크립트 이름을 확인하려면 Cloud Code를 열고 Scripts 탭을 선택합니다.

C# Monobehaviour 스크립트를 사용한 전체 연동 예시

다음 코드를 사용하여
diceSides
정수 파라미터가 있는
RollDice
스크립트를 퍼블리시할 수 있습니다.

JavaScript

const _ = require("lodash-4.17");module.exports = async ({ params, context, logger }) => { const roll = rollDice(params.diceSides); if (roll > params.diceSides) { // Log an error message with information about the exception logger.error("The roll is greater than the number of sides: " + roll); // Return an error back to the client throw Error("Unable to roll dice!"); } return { sides: params.diceSides, roll: roll, };};function rollDice(sides) { return _.random(1, sides);}
다음은 Authentication과 Cloud Code 서비스 모두를 스크립트에 연동하는 방법에 대한 전체 예시입니다.
using System.Collections.Generic;using UnityEngine;using Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.Core;public class RollDiceExample : MonoBehaviour{ // ResultType structure is the serialized response from the RollDice script in Cloud Code private class ResultType { public int Roll; public int Sides; } // Call this method to roll the dice (use a button) public async void CallMethod() { await UnityServices.InitializeAsync(); // Sign in anonymously into the Authentication service if (!AuthenticationService.Instance.IsSignedIn) await AuthenticationService.Instance.SignInAnonymouslyAsync(); // Call out to the Roll Dice script in Cloud Code var response = await CloudCodeService.Instance.CallEndpointAsync<ResultType>("RollDice", new Dictionary<string, object>( ) { { "diceSides", 6 } }); // Log the response of the script in console Debug.Log($"You rolled {response.Roll} / {response.Sides}"); }}
스크립트를 테스트하려면 Unity 에디터에서 게임 오브젝트에 스크립트를 연결한 후, Play를 선택합니다.
Start()
메서드에 다음 코드를 포함하여
CallMethod()
메서드를 호출할 수 있습니다.
public void Start(){ CallMethod();}
Cloud Code 스크립트의 응답을 원하는 유형으로 직렬화할 수 있습니다. Cloud Code SDK에 관한 자세한 내용은 Cloud Code SDK API를 참고하십시오.