Firebase
홈페이지 / 유튜브
https://firebase.google.com/?hl=ko
Firebase | Google’s Mobile and Web App Development Platform
Discover Firebase, Google’s mobile and web app development platform that helps developers build apps and games that users will love.
firebase.google.com
https://www.youtube.com/@Firebase
Firebase
The YouTube channel for all things Firebase! Learn how to build awesome apps with hands-on tutorials from the Firebase team. Firebase helps you build better mobile apps and grow your business.
www.youtube.com
이메일 회원가입 / DB 저장 가능
1. 프로젝트 만들기
2. 유니티 선택 -> 안드로이드 앱으로 등록
패키지 이름 : 고유한 패키지 이름 (전세계에서 겹치지 않아야 함) 메모리주소
3. 구성 파일 다운로드
iSO 는 사용하지 않아도 Firebase 에 오류 될 수 도 있기 때문에 설치 하기
4. SDK 받기
5. 안드로이드 설정해주기 / 패키지 주소로
6. 생성
※ 나중에 해야할 일 회원가입 닉네임 쓰고 -> 닉네임 받아서 다시 사용할 수 있도록
8. 유니티 설정해줘야 하는 것
윈도우모드에서도 사용하기 위해서는 지우고
이전에 있던 StreamingAssets 지워주고 넣어주기
구조
이메일 / 비번 입력 후 회원가입
이메일 / 비번 입력 후 로그인
내 정보 저장
로그 아웃 후
다시 로그인 하면
내 정보 셋팅
using Firebase.Auth;
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class FBAuth : MonoBehaviour
{
//using Firebase.Auth; 필요
//로그인 회원가입을 관리하는 클래스
FirebaseAuth auth;
public InputField inputEmail;
public InputField inputPassword;
void Start()
{
// auth 기능을 전체적으로 관리 실행하는 클래스 담아놓자.
//Firebase에서 싱글톤으로 만들어놓은 기능
auth = FirebaseAuth.DefaultInstance;
//로그인 / 로그아웃 상태 체크
//이벤트 형으로 되있는 델리게이트는 더해주는 형태로 가야함.
auth.StateChanged += OnChangeAuthState;
#if iDEV
inputEmail.text = "mata@gmail.com";
inputPassword.text = "mata1234";
#endif
}
//EventArgs -> using System; 필요
void OnChangeAuthState(object sender, EventArgs e)
{
//만약에 유저정보가 있으면
if (auth.CurrentUser != null)
{
//로그인 상태
print("로그인 상태");
print("Email : " + auth.CurrentUser.Email);
print("Userld : " + auth.CurrentUser.UserId);
//내정보 불러오기
FBDatabase.instance.LoadMyInfo(OnLoadMyInfo);
//결과의 정보값을 다른 곳에서 받고 싶다면 델리게이트
}
//그렇지 않으면
else
{
//로그아웃
print("로그아웃 상태");
}
}
public UserInfo myInfo;
//결과값이 불러오게 할 것임
//Json 형태로 되어있음
void OnLoadMyInfo(string strInfo)
{
myInfo = JsonUtility.FromJson<UserInfo>(strInfo);
}
//회원가입
public void OnClickSignln()
{
//내 정보를 FireBase에 보내고 응답받는 거 (코루틴으로)
StartCoroutine(CoSingnIn());
}
IEnumerator CoSingnIn()
{
//회원가입 시도 (이메일, 패스워드)
//Task<AuthResult> task = auth.CreateUserWithEmailAndPasswordAsync(inputEmail.text, inputPassword.text);
var task = auth.CreateUserWithEmailAndPasswordAsync(inputEmail.text, inputPassword.text);
//통신이 완료될때까지 기다리자 람다식으로 되어있음
yield return new WaitUntil(() => task.IsCompleted);
//만약에 예외사항이 없으면
if (task.Exception == null)
{
//회원가입 성공
print("회원가입성공");
}
//그렇지 않으면
else
{
//회원가입 실패
print("회원가입실패 : " + task.Exception.Message);
}
}
//로그아웃
public void OnClickLogout()
{
auth.SignOut();
}
//로그인
public void OnClickLogin()
{
StartCoroutine(CoLogin());
}
IEnumerator CoLogin()
{
//로그인 시도
var task = auth.SignInWithEmailAndPasswordAsync(inputEmail.text, inputPassword.text);
//통신이 완료 될때까지 기다리자
yield return new WaitUntil(() => task.IsCompleted);
//만약에 예외사항이 없다면
if (task.Exception == null)
{
//로그인 성공
print("로그인 성공");
}
//그렇지 않으면
else
{
//로그인 실패
print("로그인 실패 : " + task.Exception.Message);
}
}
}
using Firebase.Auth;
using Firebase.Database;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//유저 정보
//Json으로 만들어서 저장하라고 알려줄 것임
[System.Serializable]
public class UserInfo
{
public string userName;
public int age;
public float height;
public List<string> favoriteList;
}
public class FBDatabase : MonoBehaviour
{
public static FBDatabase instance;
//Firebase Database를 관리하는 변수
FirebaseDatabase database;
//내 정보
public UserInfo myInfo;
public void Awake()
{
instance = this;
}
void Start()
{
database = FirebaseDatabase.DefaultInstance;
//내 정보 입력
myInfo = new UserInfo();
myInfo.userName = "김현진";
myInfo.age = 25;
myInfo.height = 180;
myInfo.favoriteList = new List<string>();
myInfo.favoriteList.Add("치킨");
myInfo.favoriteList.Add("오이무침");
myInfo.favoriteList.Add("콩나물무침");
}
//정보를 저장하는 함수
public void SaveMyInfo()
{
StartCoroutine(CoSaveMyInfo());
}
IEnumerator CoSaveMyInfo()
{
// 저장 경로
//string path = "my_info/" + 유저의 유니크한 ID ;
//로그인한 유저 아이디가 할당이 되어있어야지만 가능
string path = "user_info/" + FirebaseAuth.DefaultInstance.CurrentUser.UserId;
//내 정보를 Json 형태로 바꾸자
string jsonData = JsonUtility.ToJson(myInfo);
//저장을 요청하자
var task = database.GetReference(path).SetRawJsonValueAsync(jsonData);
//통신이 완료 될때까지 기다리자.
yield return new WaitUntil(() => task.IsCompleted);
//예외사항이 없다면
if (task.Exception == null)
{
//저장 성공
print("내 정보 저장 성공");
}
//그렇지 않으면
else
{
//저장실패
print("내 정보 저장 실패 : " + task.Exception.Message);
}
}
//로그인을 하면 자동으로 호출되서 셋팅 될 수 있게
//using System; action 델리게이트
//함수가 실행 될 때 완료될 때 불러주세요 ~ 기 때문에 코루틴한테도 전달해야함.
public void LoadMyInfo(Action<string> complete)
{
StartCoroutine(CoLoadMyInfo(complete));
}
IEnumerator CoLoadMyInfo(Action<string> complete)
{
string path = "user_info/" + FirebaseAuth.DefaultInstance.CurrentUser.UserId;
//불러오기 요청
var task = database.GetReference(path).GetValueAsync();
yield return new WaitUntil(() => task.IsCompleted);
if (task.Exception == null)
{
print("불러오기 성공");
if (complete != null)
{
//성공한 정보값을 함수로 넘겨줄 것임
complete(task.Result.GetRawJsonValue());
}
}
else
{
print("불러오기 실패");
}
}
}