พอดีสนใจอยากลอง Firebase แล้วเห็นว่ามัน Support Unity3D ก็เลยเอามาลองเล่นดูครับ
มาเริ่มกันเลย
1. ให้ทำการลงทะเบียนใช้งาน Firebase และก็สร้างโปรเจ็คครับ
2. แล้วทำการสร้าง Unity Project เลยครับ
3. ทำการ โหลด API จาก Firebase ตาม link https://firebase.google.com/docs/unity/setup
4. จากนั้นทำการ Import เข้า Unity Project เลยครับ
5. จากนั้นให้ทำการสร้าง Button UI ขึ้นมา 2 ปุ่มสำหรับ Save Data และ Load Data ตามรูป
public class ToniData
{
public double body;
public string uid;
// Function อื่นๆที่จำเป็น สำหรับตัวอย่างขอเขียนง่ายๆนะครับ
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
public class FirebaseController : MonoBehaviour
{
private DatabaseReference reference;
void Start()
{
// ใช้สำหรับอ้างอิง Firebase Project
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://xxx.firebaseio.com");
// สำหรับใช้ในการอ้างอิง Firebase
reference = FirebaseDatabase.DefaultInstance.RootReference;
}
public void WriteToniData()
{
// ทำการเขียนเขียนข้อมูลว่างๆ เพื่อนำ Key มาอ้างอิง และทำการ Update ข้อมูล
string key = reference.Child("toni-test").Push().Key;
Dictionary<string, Object> childUpdates = new Dictionary<string, Object>();
// เขียนข้อมูลลง Model
ToniData tData = new ToniData();
tData.body = Random.Range(0f, 5f);
tData.uid = "Tony";
string json = JsonUtility.ToJson(tData);
// เขียนข้อมูลลง Firebase
reference.Child("toni-test").Child(key).SetRawJsonValueAsync(json);
}
public void RaadAllData()
{
FirebaseDatabase.DefaultInstance.GetReference("toni-test")
// หากข้อมูลมีการเปลี่ยนแหลงให้ทำการอ่านและแสดง
.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, ValueChangedEventArgs args)
{
if (args.DatabaseError != null)
{
Debug.LogError(args.DatabaseError.Message);
return;
}
// อ่าน Key เพื่อใช้แสดงผล
List<string> keys = args.Snapshot.Children.Select(s => s.Key).ToList();
foreach (var key in keys)
{
DisplayData(args.Snapshot, key);
}
}
// ใช้สำหรับ แสดงข้อมูลที่โหลดครับ
void DisplayData(DataSnapshot snapshot, string key)
{
string j = snapshot.Child(key).GetRawJsonValue();
ToniData u = JsonUtility.FromJson<ToniData>(j);
Debug.Log(u.uid + " " + u.body);
}
}
9. จากนั้นทำการ Assign Function ให้กับ ปุ่ม Load Data / Save Data
10. ทำการทดสอบเลยครับ
หวังว่ามีประโยชน์ไม่มากก็น้อยครับ
NO GAME NO DREAM!!!