Unity

[Unity] Unity와 Firebase연결하기

tjgpwl115 2019. 10. 24. 10:42

1. UnityFirebase 구성 파일 추가

Project Overview > 프로젝트 설정 > 최신 구성 파일 다운로드 > google-services.json클릭 > 파일을 Assets에 추가

2. Android Switch Platform

File > Build Settings > Android > Switch Platform > Player Settings 설정하기

Player Settings > Identification > Package Name 변경

3. 데이터베이스 연결하기

1) SDK 파일 다운로드

https://firebase.google.com/docs/unity/setup?hl=ko 에서 다운 받아 project > Assets에 넣기

2) Firebase SDK import

3) Script로 연결하기

* C# Script 만들기

Asset > Create > Folder > Script 폴더 생성 > C# Script 생성

<Script 전체 코드>

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
using System.Linq;

public class FirebaseTest : MonoBehaviour
{
    List GpsInfo = new List() { }; //중복 값을 없애기 위해 리스트 사용
    string gps;  //리스트에 저장될 데이터
    bool check;  //Update문에서 리스트가 한번 호출되도록(디폴트 값 : true)
    // Start is called before the first frame update
    void Start()
    {
        check = false;
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://testapp-7260f.firebaseio.com/"); // 자신의 주소 입력
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;  //datareference 접근
        StartCoroutine(GetGPSSnapshot());  //1초에 한번 함수 실행
    }
    // Update is called once per frame
    void Update()
    {
        if (check == true)
        {
            for (int i = 0; i < GpsInfo.Count; i++)
            {
                Debug.Log("GPS정보:" + GpsInfo[i]);
            }
            check = false;
        }
    }
    IEnumerator GetGPSSnapshot()  // Firebase 데이터 부르기
    {
        FirebaseDatabase.DefaultInstance.GetReference("GPS정보").GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                GpsInfo.Clear();  //리스트 초기화
                DataSnapshot levelSnapshot = task.Result;
                foreach (var rules in levelSnapshot.Children) // rules
                {
                    gps = rules.Child("경도").Value + "," + rules.Child("위도").Value; // 경도, 위도값 출력
                    GpsInfo.Add(gps);  //리스트에 데이터 추가
                    GpsInfo = GpsInfo.Distinct().ToList(); //리스트 중복 제거                
                    check = true;
                }
            }
        });
        yield return new WaitForSeconds(1); //1초마다 실행
    }
}

실행화면