Unity/서버

0630_ 서버(FireBase)

minquu 2021. 6. 30. 11:33
반응형

파이어 베이스를 한다.

 

2가지 할 것이다.

 

1.실시간 데이터 베이스

2.구글 애널리틱스 

----

 

먼저 앱 등록을 해야한다.

 

https://firebase.google.com/?gclid=CjwKCAjwieuGBhAsEiwA1Ly_nbYl-Mw1oHrXWl7cFWEJFVQFEBwdMO2GduGP8LeusTRSq0ytRlkq1RoC7YAQAvD_BwE&gclsrc=aw.ds 

 

Firebase

Firebase는 고품질 앱을 빠르게 개발하고 비즈니스를 성장시키는 데 도움이 되는 Google의 모바일 플랫폼입니다.

firebase.google.com

 

이 사이트 로그인 하기 

 

 

콘솔로이동

 

 

 

프로젝트 만들기

 

https://firebase.google.com/docs/unity/setup?hl=ko 

 

Unity 프로젝트에 Firebase 추가

Unity 프로젝트에 Firebase 추가plat_iosplat_androidplat_unity Firebase Unity SDK를 활용하여 Unity 게임을 업그레이드 해보세요. Firebase를 Unity 프로젝트에 연결하는 것이 얼마나 간편한지 보여드리기 위해 Google

firebase.google.com

이사이트도 참고

 

 

 

 

기존에 쓰던 거 선택

 

API 구글 에 있던 프로젝트임

 

국가 선택하고 만들어준다.

 

만들어 진것.

 

요금제는 스파크 여야지 무료이다..

 

 

 

 

 

클릭하면 이렇게 들어와진다.

 

패키지이름은 패키지이름으로 

 

 

 

앰 네임 적고, 등록해준다.

 

 

 

다운받아서 넣어준다.

어셋에 넣어준다.

 

다움 받으면서

 

 

https://firebase.google.com/docs/unity/setup?hl=ko 

 

Unity 프로젝트에 Firebase 추가

Unity 프로젝트에 Firebase 추가plat_iosplat_androidplat_unity Firebase Unity SDK를 활용하여 Unity 게임을 업그레이드 해보세요. Firebase를 Unity 프로젝트에 연결하는 것이 얼마나 간편한지 보여드리기 위해 Google

firebase.google.com

 

도큐먼터리를 보겠음

 

 

이러한 파이어베이스 패키지가 있음

 

 

https://firebase.google.com/docs/reference/unity?hl=ko 

 

Firebase Unity API Reference

firebase.ml.naturallanguage.translate

firebase.google.com

 

참조 문서 - 보면서 해야하는 API 문서

 

 

https://firebase.google.com/docs/auth/unity/start?hl=ko 

 

Unity에서 Firebase 인증 시작하기

Firebase 인증을 사용하면 사용자가 이메일 주소와 비밀번호 로그인 및 제휴 ID 공급업체(예: Google 로그인, Facebook 로그인)를 비롯한 1개 이상의 로그인 방법을 사용해 게임에 로그인할 수 있습니다.

firebase.google.com

 

인증 관련 도큐먼터리

 

https://firebase.google.com/docs/auth/unity/google-signin?hl=ko 

 

Google 로그인과 Unity를 사용하여 인증하기  |  Firebase

Google 로그인을 앱에 통합하여 사용자가 Google 계정으로 Firebase 인증을 받도록 설정할 수 있습니다. 시작하기 전에 Firebase 인증을 사용하려면 먼저 다음 작업이 필요합니다. Unity 프로젝트를 등록

firebase.google.com

 

구글 로그인을 보니, GPGS에서 토큰을 가져와야한다.

 

https://github.com/playgameservices/play-games-plugin-for-unity

 

playgameservices/play-games-plugin-for-unity

Google Play Games plugin for Unity. Contribute to playgameservices/play-games-plugin-for-unity development by creating an account on GitHub.

github.com

 

 

처음에 로그인할때 토큰을 가져오는 코드를 넣어야한다.

 

 

빌드하는 쪽에 추가해준다.

 

 

 

 

sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using UnityEngine.SceneManagement;

public class App : MonoBehaviour
{
    public enum ePlayMode { 
        TEST, BUILD
    }
    public Text txtAuthenicate;
    public Text test;
    public Text txtid;
    public Text txtUserName;
    public Text txtState;
    public Image thumb;
    public Button btnStart;
    public ePlayMode playMode;

    // Start is called before the first frame update
    void Start()
    {


        this.test.text = Application.version;

        if (this.playMode == ePlayMode.TEST)
        {
            this.btnStart.gameObject.SetActive(true);
        }
        else {
            this.btnStart.gameObject.SetActive(false);
        }


        this.btnStart.onClick.AddListener(() =>
        {
            //씬전환
            //SceneManager.LoadScene("GameScenes");
            SceneManager.LoadSceneAsync("GameScenes").completed += (oper) =>
            {
                var gameMain = GameObject.FindObjectOfType<GameMain>();
                gameMain.Init(Social.localUser.userName);
            };
        });

        Debug.Log("-----------------> lnit GPGS");

        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
            .RequestIdToken()
            .EnableSavedGames()
            .Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
        Debug.Log("----------------->Authenticate");

        // authenticate user:
        PlayGamesPlatform.Instance.Authenticate(SignInInteractivity.CanPromptAlways, (result) => {
            // handle results

            this.txtAuthenicate.text = result.ToString();
            if (result == SignInStatus.Success)
            {
                var localUer = (PlayGamesLocalUser)Social.localUser;
                var googleIdToken = localUer.GetIdToken();
                Debug.LogFormat("googleIdToken : {0}", googleIdToken);
            }

            Debug.Log("----------------->" + result);
            Debug.Log("----------------->" + Social.localUser);
            Debug.Log("----------------->" + Social.localUser.authenticated);

            if (Social.localUser.authenticated) {


                this.txtid.text = Social.localUser.id;
                this.txtUserName.text = Social.localUser.userName;
                this.txtState.text = Social.localUser.state.ToString();

                Debug.Log("----------------->" + Social.localUser.image);

                StartCoroutine(this.WaitForLoadThumb(() => {
                    Debug.Log(Social.localUser.image);
                    Debug.LogFormat("{0}, {1}", Social.localUser.image.width, Social.localUser.image.height);
                    this.thumb.sprite = Sprite.Create(Social.localUser.image,
                        new Rect(0, 0, Social.localUser.image.width, Social.localUser.image.height),
                        Vector2.zero);
                    this.thumb.SetNativeSize();
                }));

                this.btnStart.gameObject.SetActive(true);
            }

        });
    }
    private IEnumerator WaitForLoadThumb(System.Action callback) {
        while (true) {
            if (Social.localUser.image != null) {
                break;
            }
            yield return null;
        }
        callback();
    }
}

 

 

들어왓을때 토큰이 잘 들어오는지 테스트를 해준다.

 

cmd adb에서 로그를 본다.

 

 

하지만 이대로 하면 에러가 뜬다.

 

파이어베이스 Authentican 설정을 안해서 그렇다.

 

일단 파이어 베이스 SDK 를 넣어준다.

 

 

 

압축 풀어주기

 

닷넷 4로 집어넣기

 

오쓰만 집어넣어준다.

 

 

에섯 - 임폴트 패키지 - 커스텀 -> 저 파일 추가해주기

 

 

핸들러 어플라이 해주기 

 

리졸빙 된다.

 

 

 

하고 계속해서 콘솔로 이동해준다.

 

---

 

 

https://console.firebase.google.com/u/0/project/gpgstest-57049111/authentication/providers

 

로그인 - Google 계정

하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인

accounts.google.com

 

지금 여기에 구글 이랑 플레이 게임이 사용중지라서 작동을 안한다.

 

 

눌러보면 클라이언트 ID 와 보안 비밀번호를 넣으라고함

 

구글 API 가면 자동으로 들어옴 

 

복사해서 붙여넣기

 

 

 

비밀번호는 임시로 저장하는 것

 

아무거나 넣기 

 

 

 

구글 사용 설정 하고, 저장하면 자동으로 채워짐

 

 

 

유니티에서 

 

클라이언트 아이디도 

 

 

 

 

웹클라이언트 ID로 바꿔준다.

 

다시 빌드해서 토큰이 잘 들어오는지 확인한다.

 

 

섹세스 찍힌다.

 

----

 

 

잘 들어오는 사람들은

https://firebase.google.com/docs/auth/unity/google-signin?hl=ko 

 

 

Google 로그인과 Unity를 사용하여 인증하기  |  Firebase

Google 로그인을 앱에 통합하여 사용자가 Google 계정으로 Firebase 인증을 받도록 설정할 수 있습니다. 시작하기 전에 Firebase 인증을 사용하려면 먼저 다음 작업이 필요합니다. Unity 프로젝트를 등록

firebase.google.com

 

 

 

이 코드를 확인해서 뉴 유저 디스플레이 네임과, 유저 ID 가 들어오는 지 확인

 

 

 

추가를 해준다..

 

 if (result == SignInStatus.Success)
            {
                var localUer = (PlayGamesLocalUser)Social.localUser;
                var googleIdToken = localUer.GetIdToken();
                Debug.LogFormat("googleIdToken : {0}", googleIdToken);

                Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
                Firebase.Auth.Credential credential =
                Firebase.Auth.GoogleAuthProvider.GetCredential(googleIdToken, null);

                auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
                    if (task.IsCanceled)
                    {
                        Debug.LogError("SignInWithCredentialAsync was canceled.");
                        return;
                    }
                    if (task.IsFaulted)
                    {
                        Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                        return;
                    }

                    Firebase.Auth.FirebaseUser newUser = task.Result;
                    Debug.LogFormat("User signed in successfully: {0} ({1})",
                        newUser.DisplayName, newUser.UserId);
                });
            }

 

 

 

User signed in successfully: {0} ({1}

 

로그인데, UserId 만 찍히고, 디스플레이 네임은 안 찍힌다.

 

 

 

반응형