关于Unity和Threading Tasks的新Firebase SDK
本文关键字:的新 Firebase SDK Tasks Threading Unity 关于 | 更新日期: 2023-09-27 18:17:45
我有一个关于Unity c#和全新Firebase SDK的更普遍的问题。我看了所有的新文档,还没有看到这个问题的答案。如果你从下面的数据库中检索数据,它不允许你在这个函数中执行像Instantiate这样的方法,因为它没有发生在主线程上。你会怎么做呢?我想知道如何执行游戏功能后或而从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
}
}
};
(来自Firebase团队的Ben)
这是现在固定Stewart说下面:
https://firebase.google.com/support/release-notes/unity 1.0.1
我留下下面的代码,以防有人发现能够从后台线程封送到ui线程是有用的。一旦你安装了这个synchronizationcontext,你就可以像使用其他。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版本中修复了这个问题:https://firebase.google.com/support/release-notes/unity 1.0.1
您可以从以下网址下载最新版本:https://firebase.google.com/docs/unity/setup
欢呼,
Stewart(来自Firebase团队)