목표
우리는 위 화면에 나와있는 모든 기능들을 구현 해 볼 것이다.
계정 생성, 로그인, 게스트 접속, FACEBOOK, GOOGLE 계정으로 접속 등.
참고할 문서는 위 공식 다큐를 보면서 앞으로 어떻게 만들어 가면 되고, 공식문서를 어떻게 읽고 활용할 수 있는지
차차 알아가는 것이 목표라고 할 수 있다.
계정을 생성해보자
자, 우선 소셜 로그인 기능들은 나중에 보기로 하고, 계정 생성부터 진행해보자.
우선 만들어줘야할 것은 2가지 이다.
using PlayFab;
using PlayFab.ClientModels;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayFabAuthService
{
public static PlayFabAuthService Instance
{
get
{
if (_instance == null)
{
_instance = new PlayFabAuthService();
}
return _instance;
}
}
private static PlayFabAuthService _instance;
public PlayFabAuthService()
{
_instance = this;
}
public void RegisterPlayFabUser()
{
}
}
위에 것은 싱글톤으로 계정 생성 관련을 담당해주는 매니저 클래스를 하나 만들어줬다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoginWindowView : MonoBehaviour
{
public InputField Username;
public InputField Password;
public InputField ConfirmPassword;
public Button PlayAsGuestButton;
public Button RegisterButton;
private void Start()
{
PlayFabAuthService.Instance.RegisterPlayFabUser();
}
}
LoginWindowView는, 모노로 만들어줬고 앞으로 UI등을 담당할 것이다.
우선 코드를 보면 알겠지만 게임 시작 시, 곧바로 계정 생성을 담당해주는 매니저에 접근해서
RegisterPlayFabUser를 호출해주기로 했다. UI에 바인딩하는 것은 우선 나중에 차차 하도록하고,
계정 생성을 어떻게 하는지 보여주기 위함이다. 이제 부터 진행 할 것은 앞으로 PlayFab API 기능 개발을 하기 위해서
핵심적으로 알아둬야한다.
공식문서를 뒤져보자
우선 우리가 필요한 것은 계정생성 API이다. 이를 확인하기 위해서 구글에 검색해봐야 한다.
관련 키워드를 대충 생각해내다 보면 곧바로 공식 API Document로 넘어갈 수 있다.
그럼 이런 문서가 나올텐데 우리가 중심적으로 볼 부분은 HTTP에서 titleId.playfab.api.com 뒤에 있는 부분들이다.
Client, RegisterPlayFabUser
그리고 Request Body와
여기있는 Responses에서 200 OK 즉 통신 성공시 반환해주는 Type 만 보면된다.
아직은 감이 잘 안잡힐 수 있다. 하지만, 이제부터 어떻게 사용하는지만 보면 분명 이 글만 봤을 뿐인데 스스로
PlayFab API 문서를 읽는데 아무런 문제도 없을 것이며 혼자 스스로 문제를 해결할 수 있을 것이다.
여하튼, 이제 코드로 보자.
public void RegisterPlayFabUser()
{
PlayFabClientAPI.RegisterPlayFabUser(new RegisterPlayFabUserRequest() {
TitleId = PlayFabSettings.TitleId,
DisplayName = "Test",
Email = "Test@test.com",
Password = "123456789",
Username ="UserName"
}, (result) =>
{
Debug.Log($"계정 생성완료!{result.SessionTicket}");
},
(error)=> {
Debug.Log(error.ErrorMessage);
});
}
아까 계정 생성해주는 매니저에서, RegsiterPlayFabUser 메서드를 채워넣었다. 지금은 당연히 봐도 감이 아직 안잡힐 수 있으나 이제 하나하나 설명을 보다보면 이해가 되는 마법을 보여주겠다.
우리가 중심적으로 봐야할 코드는 PlayFabClientAPI 와 RegstierPlayFabUser이다.
아까 위에서
HTTP 부분을 다시 보면, PlayFab API는 죄다 이런식으로 사용될 수 있음을 미리 알려드리겠다.
즉 Client가 달려있는 API를 사용할려면 PlayFabClientAPI 클래스를 써서 접근해야 하는구나를 알 수 있고,
또 그 안에, RegisterPlayFabUser라는 메서드가 있구나라고 추측할 수 있다.
곧바로 다음 코드를 보면 new RegisterPlayFabuser라고 나와있는데 이는. 해당 API를 호출하기 위해서 넣어줘야하는
파라메터이다. 들어가야할 파라메터들을 살펴보자면
/// <summary>
/// Registers a new Playfab user account, returning a session identifier that can subsequently be used for API calls which
/// require an authenticated user. You must supply a username and an email address.
/// </summary>
public static void RegisterPlayFabUser(RegisterPlayFabUserRequest request, Action<RegisterPlayFabUserResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer;
var callSettings = PlayFabSettings.staticSettings;
request.TitleId = request.TitleId ?? callSettings.TitleId;
PlayFabHttp.MakeApiCall("/Client/RegisterPlayFabUser", request, AuthType.None, resultCallback, errorCallback, customData, extraHeaders, context, callSettings);
}
RegisterPlayFabUserRequest request,
Action<RegisterPlayFabUserResult> resultCallback,
Action<PlayFabError> errorCallback
이 필요하고 나머지는 default null로 안넣어줘도 된다.
여하튼 request부터 살펴보자. 저 부분을 타고 들어가면 하나의 직렬화된 클래스가 보일 것이다.
[Serializable]
public class RegisterPlayFabUserRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// An optional parameter for setting the display name for this title (3-25 characters).
/// </summary>
public string DisplayName;
/// <summary>
/// User email address attached to their account
/// </summary>
public string Email;
/// <summary>
/// Base64 encoded body that is encrypted with the Title's public RSA key (Enterprise Only).
/// </summary>
public string EncryptedRequest;
/// <summary>
/// Flags for which pieces of info to return for the user.
/// </summary>
public GetPlayerCombinedInfoRequestParams InfoRequestParameters;
/// <summary>
/// Password for the PlayFab account (6-100 characters)
/// </summary>
public string Password;
/// <summary>
/// Player secret that is used to verify API request signatures (Enterprise Only).
/// </summary>
public string PlayerSecret;
/// <summary>
/// An optional parameter that specifies whether both the username and email parameters are required. If true, both
/// parameters are required; if false, the user must supply either the username or email parameter. The default value is
/// true.
/// </summary>
public bool? RequireBothUsernameAndEmail;
/// <summary>
/// Unique identifier for the title, found in the Settings > Game Properties section of the PlayFab developer site when a
/// title has been selected.
/// </summary>
public string TitleId;
/// <summary>
/// PlayFab username for the account (3-20 characters)
/// </summary>
public string Username;
}
어, 그런데 이거 어디서 많이 보지 않았나? 그렇다 Request Body에서 봤다.
즉 객체를 만들어주고 그 안에 내용들을
TitleId = PlayFabSettings.TitleId,
DisplayName = "Test",
Email = "Test@test.com",
Password = "123456789",
Username ="UserName"
위와 같이 요구하는 자료형 타입에 맞춰 채워주면 된다.
특히나 TitleId 를 보면 Required가 True로 되어있는 즉 필수로 넣어줘야하는 것은 반드시 넣어줘야하고 나머지는
안넣어줘도 상관없다.
그, 다음 resultCallback과 errorCallback에 대해선 람다로 만들어서 넣어주고 있는 것을 볼 수 있다.
이때 result는 Responses에서 200 OK 즉 error가 아니고 성공적으로 API가 호출이 되었다면 받는 반환 값인데.
눌러서 들어가보면 이러한 데이터들을 받을 수 있다.
최종적으로 위와 같이 계정생성이 완료되었고 Session Ticket 까지 알려주는 것을 볼 수 있다.
또, PlayFab에서 Players에 들어가면 우리가 입력한 데이터들이 성공적으로 저장되었음을 확인할 수 있다.
마치며
우선은 Console로 확인하고 시작시 계정을 만들고 있지만 다음엔 이 부분을 조금 다듬어서 TextInput Field에 데이터를 입력받고 이것을 바탕으로 계정을 생성하고 소셜 로그인 까지 다룰 예정이다.
헌데.. 이 강의 까지 봤으면 뭐, 혼자서도 다 할 수 있을거라 생각한다.
'Unity > Unity&PlayFab' 카테고리의 다른 글
03. PlayFab 소셜 로그인 (페이스북) (0) | 2023.09.11 |
---|---|
(PlayFab)03.로그인 및 계정 생성 폴리싱 (0) | 2023.09.07 |
01. PlayFab SDK 설치 (0) | 2023.09.05 |
00. PlayFab 사용법과 강의 목적. (0) | 2023.09.05 |