본문 바로가기
개발/Firebase

유니티 C# 파이어베이스 리더 보드 랭킹 Leaderboard 간단 구현법

by SPNK 2022. 8. 17.
반응형

파이어베이스 SDK 다운로드

 

Unity 프로젝트에 Firebase 추가  |  Unity용 Firebase

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

firebase.google.com

 

 

압축 푼 뒤

dotnet4 / FirebaseDatabase.unitypackage 설치

 


  • 코드 작성
using Firebase;
using Firebase.Database;
using Firebase.Extensions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeaderBoardEntry
{
    public string uid;
    public int score = 0;

    public LeaderBoardEntry(string uid, int score)
    {
        this.uid = uid;
        this.score = score;
    }

    public Dictionary<string, object> ToDictionary()
    {
        Dictionary<string, object> result = new Dictionary<string, object>();
        result["uid"] = uid.ToString();
        result["score"] = score.ToString();

        return result;
    }
}

public class FirebaseDataBase : MonoBehaviour
{
    public int MaxScores = 1000;

    DatabaseReference reference;
    void Start()
    {
        reference = FirebaseDatabase.DefaultInstance.RootReference;
    }

    private void WriteNewScore(string userId, int score) //랭킹 업데이트
    {
        string key = reference.Child("scores").Push().Key;
        LeaderBoardEntry entry = new LeaderBoardEntry(userId, score);
        Dictionary<string, object> entryValues = entry.ToDictionary();

        Dictionary<string, object> childUpdates = new Dictionary<string, object>();
        childUpdates["/scores/" + key] = "0";
        childUpdates["/user-scores/" + userId + "/" + key] = "0";

        reference.UpdateChildrenAsync(childUpdates);
    }

    private void AddScoreToLeaders(string email, long score, DatabaseReference leaderBoardRef) //안전하게 랭킹 업데이트
    {
        leaderBoardRef.RunTransaction(mutableData =>
        {
            List<object> leaders = mutableData.Value as List<object>;

            if (leaders == null)
            {
                leaders = new List<object>();
            }
            else if (mutableData.ChildrenCount >= MaxScores)
            {
                long minScore = long.MaxValue;
                object minVal = null;
                foreach (var child in leaders)
                {
                    if (!(child is Dictionary<string, object>)) continue;
                    long childScore = (long)
                                ((Dictionary<string, object>)child)["score"];
                    if (childScore < minScore)
                    {
                        minScore = childScore;
                        minVal = child;
                    }
                }
                if (minScore > score)
                {
                    // The new score is lower than the existing 5 scores, abort.
                    return TransactionResult.Abort();
                }

                // Remove the lowest score.
                leaders.Remove(minVal);
            }

            // Add the new high score.
            Dictionary<string, object> newScoreMap =
                             new Dictionary<string, object>();
            newScoreMap["score"] = score;
            newScoreMap["email"] = email;
            leaders.Add(newScoreMap);
            mutableData.Value = leaders;
            return TransactionResult.Success(mutableData);
        });
    }
}
반응형

댓글