Skip to content

Instantly share code, notes, and snippets.

@SohanChy
Created January 30, 2023 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SohanChy/54d51fff663ff19419600f8f9ef0e606 to your computer and use it in GitHub Desktop.
Save SohanChy/54d51fff663ff19419600f8f9ef0e606 to your computer and use it in GitHub Desktop.
Firebase Unity Study Sample
using ExtensionMethods;
using Firebase;
using Firebase.Database;
using Firebase.Extensions;
using PointSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using static UnityEngine.JsonUtility;
public class RTDB : MonoBehaviour
{
DatabaseReference RealtimeDB;
public GameManager GM;
public static string[] dataLogArr;
void Start()
{
RealtimeDB = FirebaseDatabase.DefaultInstance.RootReference.Child("State");
RealtimeDB.ValueChanged += HandleStateChanged;
StartCoroutine(GetCurrentState());
}
void HandleStateChanged(object sender, ValueChangedEventArgs args)
{
if (args.DatabaseError == null)
{
StartCoroutine(GetCurrentState());
}
}
System.Collections.IEnumerator GetCurrentState()
{
var DBTask = RealtimeDB.GetValueAsync();
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
DataSnapshot snapshot = DBTask.Result;
if (snapshot.Exists)
{
Technique = snapshot.Child("technique").Value.ToString();
restart = (bool)snapshot.Child("restart").Value;
if (restart) {
GM.restart();
restart = false;
StartCoroutine(UpdateState());
}
}
public static System.Collections.IEnumerator AddDataLog(string studyId, StudyDataLog log)
{
DatabaseReference RealtimeDB = FirebaseDatabase.DefaultInstance.RootReference.Child("studylogs");
string ts = log.timestamp.ToString().Replace("/","-");
log.curveCombo = curveCombo;
var DBTask = RealtimeDB.Child(studyId).Child("participant_"+ log.ParticipantId).Child(ts).SetValueAsync(log.toCSVString());
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
}
public static System.Collections.IEnumerator LogTrialSetting(string studyId, StudyDataLog log)
{
DatabaseReference RealtimeDB = FirebaseDatabase.DefaultInstance.RootReference.Child("studylogs");
string ts = log.timestamp.ToString().Replace("/", "-");
var DBTask = RealtimeDB.Child(studyId).Child("participant_" + log.ParticipantId + "_settings").Child(ts).SetValueAsync(log.toCSVString() + "," + StudyDataLog.wrap(log.dhCombos));
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
}
System.Collections.IEnumerator UpdateState()
{
var DBTask1 = RealtimeDB.Child("Vars").Child("curveArmDistance").SetValueAsync(somevalue);
var DBTask2 = RealtimeDB.Child("restart").SetValueAsync(restart);
yield return new WaitUntil(predicate: () => DBTask1.IsCompleted && DBTask2.IsCompleted && DBTask3.IsCompleted && DBTask4.IsCompleted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment