Unity
NCMB를 이용한 네트워크 구현2
기리도
2022. 2. 25. 15:58
728x90
저번 포스팅에 이어서 네트워크를 좀 더 연습하려고 한다. 이번에는 실제로 게임에 적용해 보기 위해 샘플 게임을 가져왔다.
먼저 저번과 마찬가지로 NCMBManager와 NCMBSettings 스크립트를 각각 빈 게임 오브젝트에 붙여주고 Application Key와 Client Key를 넣어줬다.
그런 뒤 적당히 메인 화면을 만들어준다.
대충 이런 느낌이다. 사용한 오브젝트는 다음과 같다.
간단하게나마 설명하자면 ControlSystem에 로그인과 계정 생성 등의 기능을 구현한 LoginSignUp 스크립트를 넣어 놓고 Button에서 OnClickEvent를 이용해 사용하는 방식이다. LoginSignUp의 코드는 다음과 같다.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using NCMB;
public class LoginSignUp : MonoBehaviour
{
public InputField TextUserID, TextUserPass;
public Text Notice;
public GameObject[] ButtonUI;
void Start()
{
OnLogInMode(); //로그인 화면부터 시작
}
public IEnumerator SignupSequence()
{
string UserID = TextUserID.text;
string UserPass = TextUserPass.text;
if (string.IsNullOrEmpty(UserID) || string.IsNullOrEmpty(UserPass))
{
Notice.text = "아이디나 비밀번호를 입력하지 않았습니다.";
yield break;
}
else if (UserPass.Length < 8)
{
Notice.text = "비밀번호는 여덟 자리 이상이어야 합니다.";
yield break;
}
yield return SignUpCoroutine(UserID, UserPass);
}
public IEnumerator SignUpCoroutine(string UserId, string UserPass)
{
NCMBUser User = new NCMBUser();
User.UserName = UserId;
User.Password = UserPass;
User.Add("Nick", UserId);
User.Add("cash", 0);
User.Add("Score", 0);
bool isConnecting = true;
User.SignUpAsync((NCMBException e) => {
if (e != null)
{
Notice.text = "통신에 실패했습니다.";
isConnecting = false;
}
});
while (isConnecting) { yield return null; }
}
public IEnumerator LogInSequence()
{
string UserID = TextUserID.text;
string UserPass = TextUserPass.text;
if (string.IsNullOrEmpty(UserID) || string.IsNullOrEmpty(UserPass))
{
Notice.text = "아이디나 비밀번호를 입력하지 않았습니다.";
yield break;
}
yield return LoginCorutine(UserID, UserPass);
}
public IEnumerator LoginCorutine(string UserID, string UserPass)
{
NCMBUser.LogInAsync(UserID, UserPass, (NCMBException e) =>
{
if (e != null)
{
Notice.text = "통신에 실패했습니다.";
}
else
{
SceneManager.LoadScene("MainSCene", LoadSceneMode.Single); //로그인 성공 시 게임 시작
}
});
yield return null;
}
public void OnClickLogIn()
{
if (Application.internetReachability == NetworkReachability.NotReachable)
{
Notice.text = "인터넷이 연결되지 않았습니다.";
return;
}
StartCoroutine(LogInSequence());
}
public void OnClickSignUp()
{
if (Application.internetReachability == NetworkReachability.NotReachable)
{
Notice.text = "인터넷이 연결되지 않았습니다.";
return;
}
StartCoroutine(SignupSequence());
OnLogInMode();
}
//로그인 화면에 필요한 UI만 켜주기
public void OnLogInMode()
{
ButtonUI[0].SetActive(true);
ButtonUI[1].SetActive(false);
TextUserID.text = null;
TextUserPass.text = null;
}
public void OnSignUpMode()
{
ButtonUI[0].SetActive(false);
ButtonUI[1].SetActive(true);
TextUserID.text = null;
TextUserPass.text = null;
}
}
여기까지 했으면 거의 다 했다. 잘 작동하는지 알아보기 위해 실행한 뒤 계정을 생성해 봤다.
정상적으로 계정이 생성된 걸 확인할 수 있다. 이제 생선한 계정으로 샘플 게임에 로그인 해 보자.
728x90