유니티 네트워크 파이어베이스 설정

JHO·2024년 11월 18일
0

유니티 3D

목록 보기
9/14

1. 파이어베이스 설정


1-1. 파이어베이스 설정


2. 유니티 프로젝트 설정


2-1. 백엔드와 유니티 연동.

2-2. UnitySDK파일 포함.

  • 파이어베이스를 적용하기 위한 FirebaseAnalytics 패키지 포함.
  • 인증 관련도 적용하기 위해서 FirebaseAuth패키지도 포함.

3. 자주 사용하는 파이어베이스 함수


3-1. BackendManager

using Firebase;
using Firebase.Auth;
using Firebase.Database;
using Firebase.Extensions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackendManager : MonoBehaviour
{
    public static BackendManager Instance { get; private set; }
    private FirebaseApp app;
    public static FirebaseApp App { get { return Instance.app; } }
    private FirebaseAuth auth;
    public static FirebaseAuth Auth {  get { return Instance.auth; } }
    private FirebaseDatabase database;
    public static FirebaseDatabase Database {  get { return Instance.database; } }
    private void Awake()
    {
        CreateSingleton();
    }
    private void Start()
    {
        CheckDependency();
    }
    private void CreateSingleton()
    {
        if(Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
    //호환성 여부 체크
    private void CheckDependency()
    {
        // checkandfixDependenciesasync가 요청, continuewithonmainTHread가 반응.
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
        {
            //결과가 사용가능하면
            if (task.Result == DependencyStatus.Available)
            {
                // Create and hold a reference to your FirebaseApp,
                // where app is a Firebase.FirebaseApp property of your application class.
                app = FirebaseApp.DefaultInstance;
                auth = FirebaseAuth.DefaultInstance;
                database = FirebaseDatabase.DefaultInstance;
                // Set a flag here to indicate whether Firebase is ready to use by your app.
                Debug.Log("Firebase dependencies check success");
            }
            else
            {
                Debug.LogError($"Could not resolve all Firebase dependencies: {task.Result}");
                // Firebase Unity SDK is not safe to use here.
                app = null;
                //인증실패햇으므로
                auth = null;
                database = null;
            }
        });
    }  
}

3-2. 가입

string email = emailInputField.text;
string pass = passwordInputFIeld.text;
BackendManager.Auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWithOnMainThread(task =>
{
    if (task.IsCanceled)
    {
        Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
        return;
    }
    if (task.IsFaulted)
    {
        Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
        return;
    }
    // Firebase user has been created.
    AuthResult result = task.Result;
    Debug.Log($"Firebase user created successfully: {result.User.DisplayName} ({result.User.UserId})");
});

3-3. 로그인

string email = emailInputField.text;
string pass = passwordInputFIeld.text;
BackendManager.Auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWithOnMainThread(task =>
{
    if (task.IsCanceled)
    {
        Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
        return;
    }
    if (task.IsFaulted)
    {
        Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
        return;
    }
    AuthResult result = task.Result;
    Debug.Log($"User signed in successfully: {result.User.DisplayName} ({result.User.UserId})");
});

3-4. 인증 삭제

FirebaseUser user = BackendManager.Auth.CurrentUser;
if (user == null)
    return;
user.DeleteAsync().ContinueWithOnMainThread(task =>
{
    if (task.IsCanceled)
    {
        Debug.LogError("DeleteAsync was canceled.");
        return;
    }
    if (task.IsFaulted)
    {
        Debug.LogError("DeleteAsync encountered an error: " + task.Exception);
        return;
    }
    Debug.Log("User deleted successfully.");
});

3-5. 사용자 프로필 가져오기

FirebaseUser user = BackendManager.Auth.CurrentUser;
if (user == null)
    return;
string name = user.DisplayName;         // 공개용 이름
string email = user.Email;              // 이메일 주소
bool verified = user.IsEmailVerified;   // 이메일 인증여부
System.Url url = user.PhotoUrl;         // 사진 URL 주소
string uid = user.UserId;               // 고유 아이디 (파이어베이스 사용자 식별용)

3-6. 사용자 프로필 업데이트

FirebaseUser user = BackendManager.Auth.CurrentUser;
if (user == null)
    return;
UserProfile profile = new UserProfile
{
    DisplayName = "공개용 이름",
    PhotoUrl = new System.Uri("https://example.com/profile.jpg"),
};
user.UpdateUserProfileAsync(profile).ContinueWithOnMainThread(task =>
{
    if (task.IsCanceled)
    {
        Debug.LogError("UpdateUserProfileAsync was canceled.");
        return;
    }
    if (task.IsFaulted)
    {
        Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception);
        return;
    }
    Debug.Log("User profile updated successfully.");
});

3-7. 인증 메일 보내기

FirebaseUser user = BackendManager.Auth.CurrentUser;
if (user == null)
    return;
user.SendEmailVerificationAsync().ContinueWithOnMainThread(task =>
{
    if (task.IsCanceled)
    {
        Debug.LogError("SendEmailVerificationAsync was canceled.");
        return;
    }
    if (task.IsFaulted)
    {
        Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception);
        return;
    }
    Debug.Log("Email sent successfully.");
});

3-8. ReLoad 하기

 BackendManager.Auth.CurrentUser.ReloadAsync().ContinueWithOnMainThread(task =>
 {
     if (task.IsCanceled)
     {
         Debug.LogError("ReloadAsync was canceled");
         return;
     }
     if (task.IsFaulted)
     {
         Debug.LogError($"ReloadAsync encountered an error: {task.Exception.Message}");
         return;
     }
     //리로드해야 갱신이 됨.
     if (BackendManager.Auth.CurrentUser.IsEmailVerified == true)
     {
         Debug.Log("인증 확인");
         nickNamePanel.gameObject.SetActive(true);
         gameObject.SetActive(false);
     }    
 });
  • 이메일로 인증확인 보내고,나서 확인이 되었는지 체크할 필요가 있기 때문에 이런 경우, ReLoad를 사용.
 //이메일 인증
 private void SendVerifyMail()
 {
     FirebaseUser user = BackendManager.Auth.CurrentUser;
     user.SendEmailVerificationAsync().ContinueWithOnMainThread(task =>
     {
         if (task.IsCanceled)
         {
             Debug.LogError("SendEmailVerificationAsync was canceled.");
             gameObject.SetActive(false);
             return;
         }
         if (task.IsFaulted)
         {
             Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception);
             gameObject.SetActive(false);
             return;
         }
         Debug.Log("Email sent successfully.");
         checkVerifyRoutine = StartCoroutine(CheckVerifyRoutine());
     });
 }
 Coroutine checkVerifyRoutine; 
 IEnumerator CheckVerifyRoutine()
 {
     WaitForSeconds delay = new WaitForSeconds(3f);
     while (true)
     {
         BackendManager.Auth.CurrentUser.ReloadAsync().ContinueWithOnMainThread(task =>
         {
             if (task.IsCanceled)
             {
                 Debug.LogError("ReloadAsync was canceled");
                 return;
             }
             if (task.IsFaulted)
             {
                 Debug.LogError($"ReloadAsync encountered an error: {task.Exception.Message}");
                 return;
             }
             //리로드해야 갱신이 됨.
             if (BackendManager.Auth.CurrentUser.IsEmailVerified == true)
             {
                 Debug.Log("인증 확인");
                 nickNamePanel.gameObject.SetActive(true);
                 gameObject.SetActive(false);
             }          
         });
         //인증 확인 
         yield return delay;
     }
 }
  • 코루틴을 통해 주기적으로 이메일 인증이 확인되었는지 체크.

3-9. 비밀번호 재설정 이메일 보내기

string email = "testemail@gmail.com";
BackendManager.Auth.SendPasswordResetEmailAsync(email).ContinueWithOnMainThread(task =>
{
    if (task.IsCanceled)
    {
        Debug.LogError("SendPasswordResetEmailAsync was canceled.");
        return;
    }
    if (task.IsFaulted)
    {
        Debug.LogError("SendPasswordResetEmailAsync encountered an error: " + task.Exception);
        return;
    }
    Debug.Log("Password reset email sent successfully.");
});

3-10. 오류 원인 불러오기

  • 파이어베이스 인증 설정 중 사용자 작업에서 이메일 열거 보호를 해제.
    -> 열거 보호가 해제 되어야 원인을 파악 가능.

3-11. 이메일인증한user불러오기

profile
개발노트

0개의 댓글