我对Unity C#和全新的Firebase SDK有一个更普遍的问题。我已查看了所有新文档,但尚未找到答案。如果从下面的数据库中检索数据,它不允许您在此函数中执行Instantiate之类的方法,因为它不会发生在主线程上。你会怎么做呢? TLDR我想知道如何在从Firebase检索内容之后或同时执行游戏功能。
FirebaseDatabase.DefaultInstance
.GetReference("Scenes").OrderByChild("order")
.ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
if (e2.DatabaseError != null) {
Debug.LogError(e2.DatabaseError.Message);
}
scenes = asset.text.Split('\n');
return;
}
if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0) {
sceneCollection.Clear();
foreach (var childSnapshot in e2.Snapshot.Children) {
var sceneName = childSnapshot.Child("name").Value.ToString();
sceneCollection.Add( new SceneItem(sceneName, 0));
// I WANTED TO INSTANTIATE SOMTHING HERE
}
}
};
答案 0 :(得分:3)
(来自Firebase团队的Ben)
现在已经解决了这个问题,斯图尔特在下面说:
https://firebase.google.com/support/release-notes/unity#1.0.1
我离开下面的代码,以防有人发现能够从后台线程封送到ui线程有用。安装此同步上下文后,您可以像使用任何其他.Net SynchronizationContext一样使用它:
https://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext(v=vs.110).aspx
UnitySynchronizationContext.Install();
class UnitySynchronizationContext : SynchronizationContext {
static UnitySynchronizationContext _instance = null;
GameObject gameObject;
Queue<Tuple<SendOrPostCallback, object>> queue;
private UnitySynchronizationContext() {
gameObject = new GameObject("SynchronizationContext");
gameObject.AddComponent<SynchronizationContextBehavoir>();
queue =
gameObject.GetComponent<SynchronizationContextBehavoir>()
.Queue;
}
public static void Install() {
if (SynchronizationContext.Current == null)
{
if (_instance == null)
{
_instance = new UnitySynchronizationContext();
}
SynchronizationContext.SetSynchronizationContext(_instance);
}
}
public override void Post(SendOrPostCallback d, object state) {
lock (queue)
{
queue.Enqueue(new Tuple<SendOrPostCallback, object>(d, state));
}
}
class SynchronizationContextBehavoir : MonoBehaviour {
Queue<Tuple<SendOrPostCallback, object>> callbackQueue
= new Queue<Tuple<SendOrPostCallback, object>>();
public Queue<Tuple<SendOrPostCallback, object>>
Queue { get { return callbackQueue; }}
IEnumerator Start() {
while (true)
{
Tuple<SendOrPostCallback, object> entry = null;
lock (callbackQueue)
{
if (callbackQueue.Count > 0)
{
entry = callbackQueue.Dequeue();
}
}
if (entry != null && entry.Item1 != null)
{
try {
entry.Item1(entry.Item2);
} catch (Exception e) {
UnityEngine.Debug.Log(e.ToString());
}
}
yield return null;
}
}
}
}
答案 1 :(得分:0)
我们已在1.0.1版本中修复了此问题: https://firebase.google.com/support/release-notes/unity#1.0.1
您可以从以下位置下载最新版本: https://firebase.google.com/docs/unity/setup
干杯,
Stewart(来自Firebase团队)