250x250
기리도
기리도의 개발새발 개발 일지
기리도
전체 방문자
오늘
어제
  • 분류 전체보기 (44)
    • Unity (6)
      • 모듈식 프로그래밍 (1)
    • C# (10)
    • 자료구조,알고리즘 (2)
    • 운영체제 (10)
      • 공룡책 (3)
      • 그림으로 쉽게 배우는 운영체제(인프런 강의) (7)
    • 리팩토링 (1)
    • 네트워크 (13)
      • 네트워크 장비 (13)
    • C, C++ 문법 (1)
      • 기타 (0)
      • C (1)
      • C++ (0)
    • 디자인 패턴 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 개발
  • 인프런
  • OS
  • 탄환
  • 스위치
  • 프로그래밍
  • 게임개발
  • 길찾기
  • 브릿지
  • 네트워킹
  • 알고리즘
  • 개발공부
  • 네트워크
  • 통신
  • 공부
  • 유니티
  • Unity
  • 운영체제
  • C#
  • 네트워크 게임

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
기리도

기리도의 개발새발 개발 일지

NCMB를 이용한 유니티 네트워크 구현하기
Unity

NCMB를 이용한 유니티 네트워크 구현하기

2022. 2. 23. 18:18
728x90

  NCMB란 일본 회사가 제공하는 mBaas로, 'nifcloud mobile backend'를 말한다. 오늘은 제목처럼 NCMB를 이용해 유니티 네트워크를 구현해 볼 거다.

  *mBaas(Mobile Backend as a Service)

 

NCMB를 이용하려면 계정을 생성하고 플러그인을 다운로드 해야 한다.
https://console.mbaas.nifcloud.com/login
 

ニフクラ mobile backend

 

console.mbaas.nifcloud.com

위 링크에서 계정을 만들어 준다.

https://github.com/NIFCloud-mbaas/ncmb_unity/releases
 

Releases · NIFCLOUD-mbaas/ncmb_unity

ニフクラ mobile backend Unity SDK. Contribute to NIFCLOUD-mbaas/ncmb_unity development by creating an account on GitHub.

github.com

플러그인은 여기서 받을 수 있다. 플러그인을 받았으면 Import를 해주자. 그럼 아래처럼 NCMB 폴더가 생기고 그 안에 스크립트 두 개와 다시 폴더 두 개가 있는 걸 볼 수 있다.
  다음으로 <NCMBManager>와 <NCMBSettings>라는 이름으로 빈 게임 오브젝트를 생성하고 그 안에 각각  <NCMBManager> 스크립트와 <NCMBSettings> 스크립트를 넣어줬다.
  <NCMBSettings> 스크립트를 보면 Application Key와 xlient Key를 입력하는 곳이 있는데 이 키는 nifcloud 사이트의 우측 상단에 있는 App Settings 를 누르면 확인할 수 있다.
 

 

  데이터를 저장하기 위해 빈 오브젝트에 <DataSave>

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NCMB;

public class DataSave : MonoBehaviour
{
    void Start()
    {
        dataPlayerSave("Player1", 200, 10);
        dataPlayerSave("Player2", 100, 20);

    }
    public void dataPlayerSave(string Username, int Score, int Lv)
    {
        NCMBObject obj = new NCMBObject("PlayerData"); //PlayerData 라는 이름으로 데이터 시트 생성
        obj.Add("PlayerName", Username); // 항목 추가
        obj.Add("Score", Score);
        obj.Add("PlayerLevel", Lv);

        NCMBCallback callback = DoAfterSave;

        obj.SaveAsync(callback);
    }

    void DoAfterSave(NCMBException e) //에러가 없으면 e는 null이 되고 에러가 있으면 에러의 정보가 e에 담긴다
    {
        if (e != null)
        {
            Debug.Log("전송실패");
        }
        else
        {
            Debug.Log("데이터를 저장했습니다");
        }
    }
}

  스크립트를 넣었다. 실행하면 "데이터를 저장했습니다"라는 로그가 뜰 것이고 서버에도 데이터가 올라갈 것이다.

  정상적으로 등록된 모습이다. 그럼 이제 데이터를 불러오는 작업도 해보자. 마찬가지로 빈 오브젝트를 생성한 뒤 <LoadData> 스크립트를 추가한다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NCMB;
public class LoadData : MonoBehaviour
{
    void Start()
    {
        findScoreData(150);
    }
    private void findScoreData(int higherthan)
    {
        NCMBQuery<NCMBObject> query = new NCMBQuery<NCMBObject>("PlayerData");

        //조건 설정
        query.WhereGreaterThan("Score", higherthan);
        query.FindAsync((List<NCMBObject> objlist, NCMBException e) =>
        {
            {
                if (e != null)
                {

                }
                else
                {
                    foreach (NCMBObject obj in objlist)
                    {
                        Debug.Log("PlayerName : " + obj["PlayerName"] + " " + "Score : " + obj["Score"]);
                    }
                }
            }
        });
    }
}

  실행하면 Player1의 데이터만 불러오는 걸 확인할 수 있다. 마지막으로, <UserSignUpandLogIn> 이라는 이름으로 빈 게임 오브젝트를 생성하고 <UserSignUpandLogIn> 스크립트를 넣어준다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NCMB;

public class UserSignUpandLogIn : MonoBehaviour
{
    public string UserID;
    public string PassWord;
    public string Email;

    void Start()
    {
        fnSignUp(UserID, PassWord, Email);
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            LogOut();
        }
    }

    public void fnSignUp(string userID, string password, string email)
    {
        NCMBUser user = new NCMBUser();

        user.UserName = UserID;
        user.Password = password;
        user.Email = email;

        user.SignUpAsync((NCMBException e) => {
            if (e != null)
            {
                LogIn(userID, password);
                Debug.Log("로그인합니다");
            }
            else
            {
                Debug.Log("신규 등록을 성공했습니다");
            }
        });
    }
    public void LogIn(string userID, string password)
    {
        NCMBUser.LogInAsync(userID, password, (NCMBException e) =>
        {
            if (e != null)
            {
                Debug.Log("로그인 실패");
            }
            else
            {
                Debug.Log("로그인 성공");
                SetPoint(100);
            }
        });
    }

    void SetPoint(int num)
    {
        NCMBUser.CurrentUser["Point"] = num;
        NCMBUser.CurrentUser.SaveAsync((NCMBException e) =>
        {
            if (e != null)
            {
                Debug.Log("데이터 저장 실패");
            }
            else
            {
                Debug.Log("데이터 저자 성공");
            }
        }
        );
    }
    public void LogOut()
    {
        NCMBUser.LogOutAsync((NCMBException e) =>
        {
            if (e != null)
            {
                Debug.Log("로그아웃 실패");
            }
            else
            {
                Debug.Log("로그아웃 성공");
            }
        });
    }

}

  로그인, 로그아웃, 계정 생성 기능을 구현한 코드. 나중에 실제로 네트워크 게임을 만들 때 좀 더 깊게 다뤄 보겠다.

728x90

'Unity' 카테고리의 다른 글

[Unity]이벤트(Event)로 키 입력 관리하기  (0) 2022.06.16
NCMB를 이용한 네트워크 구현2  (0) 2022.02.25
방향탄  (0) 2022.02.11
탄환의 속도  (0) 2022.02.04
    'Unity' 카테고리의 다른 글
    • [Unity]이벤트(Event)로 키 입력 관리하기
    • NCMB를 이용한 네트워크 구현2
    • 방향탄
    • 탄환의 속도
    기리도
    기리도
    공부한 내용을 정리해서 올리는 블로그입니다.

    티스토리툴바