Unity Firebase

[Unity Firestore] 데이터 읽기 쓰기

때류기 2023. 11. 9. 16:47

 

 

현재 진행중인 프로젝트에 사용할 파이어베이스를 배워보고있습니다.

설치방법은 넘어가며 간단하게 파이어스토어에서 값을 받고 쓸 수 있는 코드를 작성해보겠습니다.

 

 

작성 코드

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

public class Datas : MonoBehaviour
{

    FirebaseFirestore db;

    private void Start()
    {
        //FirebaseFirestore기본값의 인스턴스를 가져온다.
        db = FirebaseFirestore.DefaultInstance;
        ReadData();
        WriteData();
    }

    public void WriteData()
    {
        Debug.Log("데이터를 저장합니다.");

        //Firestore Database에서 ItemData컬렉션 -> TestItem문서 항목을 가져온다.(직접만들어야함) 
        DocumentReference docRef = db.Collection("ItemData").Document("TestItem");

        //딕셔너리를 생성해 정보를 넣는다.
        Dictionary<string, object> data = new Dictionary<string, object>()
        {
                { "Id", 1 },
                { "Description", "아이템 설명" },
                { "Name", "아이템 이름" }
        };

        //비동기로 가져온 문서를 완전히 바꾸거나 필드를 병합하여 문서의 데이터를 변경
        docRef.SetAsync(data).ContinueWithOnMainThread(task =>
        {
            Debug.Log("쓰기완료!");
        });
    }

    public void ReadData()
    {
        Debug.Log("데이터를 불러옵니다.");
        CollectionReference itemRef = db.Collection("ItemData");

        //Task< DocumentSnapshot >문서의 스냅샷을 비동기적으로 가져옵니다.
        //또한 지정된 작업이 완료되고 지정된 연속 함수가 Unity의 메인스레드에서 호출되면 완료되는 작업을 반환
        itemRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
        {

            QuerySnapshot snapshot = task.Result;
            //불러온 문서들의 집합을 반복문을 통해 한번씩 접근 후 딕셔너리 형태로 변환한다. 
            foreach(DocumentSnapshot document in snapshot.Documents)
            {
                Debug.LogFormat("Item: {0}", document.Id);
                Dictionary<string, object> dic = document.ToDictionary();
                Debug.LogFormat("ID: {0}", dic["Id"]);
                Debug.LogFormat("Name: {0}", dic["Name"]);
                Debug.LogFormat("Description: {0}", dic["Description"]);
            }
        });
    }
}

 

코드 실행전 파이어스토어 상태

 

코드 실행 후 콘솔 로그

 

변경 후 파이어 스토어 상태