https://console.firebase.google.com/?hl=ko

 

로그인 - Google 계정

이메일 또는 휴대전화

accounts.google.com

 

 

다운로드 하면 이렇게 제이슨 파일이 만들어지고 이것을 프로젝트에 넣어주면 된다.

 

Firebase SDK도 설치

압축을 풀면 이렇게 생긴다.

여기서 필요한 것을 가져다가 쓰면 된다.

현재는 FirebaseDatabase를 사용할 것이다.

가장 가까운 싱가포르 선택

 

IOS Build 선택 후 다운로드

설치 후 다시 프로젝트로 들어간다.

 

창이 나오면 Yes만 클릭하면 된다.

 

이름으로 추가 를 선택 후

com.unity.nuget.newtonsoft-json를 넣는다.

 

스크립트 를 만든후 빈 오브젝트에 할당

using Firebase;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DBManager : MonoBehaviour
{
    [SerializeField] private string databaseUrl;

    private void Start()
    {
       FirebaseApp.DefaultInstance.Options.DatabaseUrl
            = new System.Uri(databaseUrl);
    }

}

게임정보

유저 아이디

점수

GameInfo

userId

score

이 주소를 복사 한후

여기에 넣어주면 된다.

 

새 스크립트 생성 및 수정

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameMain : MonoBehaviour
{
    [SerializeField] private string userId;
    [SerializeField] private int score;

    void Start()
    {
        SaveGame();
    }

    public void SaveGame()
    {
        Debug.Log("SaveGame");

        GameInfo gameInfo = new GameInfo(userId, score);    //저장 객체 만들기 
        string json = JsonConvert.SerializeObject(gameInfo);  //직렬화 

        Debug.Log($"{json}");

        //저장 
        DBManager.instance.SaveData(json);
    }
}

 

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

public class GameInfo
{
    public string userId;
    public int score;

    //생성자 
    public GameInfo(string userId, int score) {
        this.userId = userId;
        this.score = score;
    }
}

 

using Firebase;
using Firebase.Database;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DBManager : MonoBehaviour
{
    [SerializeField] private string databaseUrl;

    public static DBManager instance;

    private void Awake()
    {
        instance = this;    //싱글톤 
    }

    void Start()
    {
        FirebaseApp.DefaultInstance.Options.DatabaseUrl
            = new System.Uri(databaseUrl);
    }

    public async void SaveData(string json)
    {
        Debug.Log("SaveData");

        //DB의 최상단 디렉토리를 참조 
        DatabaseReference dbRef = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log($"dbRef: {dbRef}");

        //비동기 메서드때문에 완료 될때까지 대기
        await dbRef.SetRawJsonValueAsync(json);

        Debug.Log("데이터 저장 완료");
    }
}

 

------------------------- 오류가 계속 나서 다시 시작 ------------------------

이 세개를 빼고 library, obj 같이 생성시 생기는 파일들을 모두 삭제하였다.

Firebase 폴더가 삭제되지 않으면 오픈 윈도우로 들어가서 삭제해보고

그래도 관리자 권한때문에 삭제되지 않으면 재부팅하면 된다.

 

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

public class User
{
    public string username;
    public string email;

    public User()
    {
    }

    public User(string username, string email)
    {
        this.username = username;
        this.email = email;
    }
}

 

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

public class GameInfo
{
    public string userId;
    public int score;

    //생성자 
    public GameInfo(string userId, int score)
    {
        this.userId = userId;
        this.score = score;
    }
}

 

using Firebase.Database;
using Firebase.Extensions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class GameMain : MonoBehaviour
{
    DatabaseReference mDatabaseRef;
    void Start()
    {
        Debug.Log($"Firebase.FirebaseApp.DefaultInstance: {Firebase.FirebaseApp.DefaultInstance}");
        // Get the root reference location of the database.

        mDatabaseRef = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log($"reference : {mDatabaseRef}");

        writeNewUser("hong", "홍길동", "hong@gmail.com");


    }

    private void writeNewUser(string userId, string name, string email)
    {
        User user = new User(name, email);
        string json = JsonUtility.ToJson(user);

        mDatabaseRef.Child("Users").SetRawJsonValueAsync(json);
        CheckAndFixDependenciesAsync();
    }

    private void CheckAndFixDependenciesAsync()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
            var dependencyStatus = task.Result;
            if (dependencyStatus == Firebase.DependencyStatus.Available)
            {
                // Create and hold a reference to your FirebaseApp,
                // where app is a Firebase.FirebaseApp property of your application class.
                var app = Firebase.FirebaseApp.DefaultInstance;
                Debug.Log($"app : {app}");


                // Set a flag here to indicate whether Firebase is ready to use by your app.
            }
            else
            {
                UnityEngine.Debug.LogError(System.String.Format(
                  "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
                // Firebase Unity SDK is not safe to use here.
            }
        });
    }

}

 

using Firebase;
using Firebase.Database;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DBManager : MonoBehaviour
{
    [SerializeField] private string databaseUrl;

    public static DBManager instance;

    private void Awake()
    {
        instance = this;    //싱글톤 
    }


    public void Init()
    {
        FirebaseApp.DefaultInstance.Options.DatabaseUrl
            = new System.Uri(databaseUrl);

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {

            FirebaseApp app = FirebaseApp.DefaultInstance;

            if (app != null)
            {
                Debug.Log("DefaultInstance를 찾을수 없습니다.");
            }
            else
            {
                Debug.Log("초기화가 정상적으로 되었습니다.");
            }
        });
    }

    public async void SaveData(string json)
    {
        Debug.Log("SaveData");

        //DB의 최상단 디렉토리를 참조 
        DatabaseReference dbRef = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log($"dbRef: {dbRef}");

        //비동기 메서드때문에 완료 될때까지 대기
        await dbRef.SetRawJsonValueAsync(json);

        Debug.Log("데이터 저장 완료");
    }
}

 

 

 

지정된 파이어베이스 주소로 데이터가 잘 들어옴을 확인할 수 있다.

 

 

 

 

+ Recent posts