Здравствуйте, я пытаюсь создать простое приложение для обмена сообщениями с Unity, но у меня возникают проблемы с этим.
Итак, я пытаюсь заполнить список последних сообщений, создавая кнопки (В режиме реального времени) я сначала запускаю LoadRecentMessages (), чтобы получить ваши идентификаторы чата в вашем "users_chat_info" из базы данных Firebase, затем он запускает GetRecentMsgs (), который получает самое последнее сообщение в вашем чате, которое получаетданные из пути к базе данных Firebase "chat"> "chat_room"> "(SomeGeneratedKey)"> "m_recent" , затем создается кнопка с этой информацией.Как вы можете видеть ниже, вот дерево данных, которое я использую, чтобы вы могли понять, как оно работает (DataTree)
Теперь проблема в том, что этосоздавая кнопки дважды по некоторым причинам.И я запустил журнал отладки, и chatIds имеет счетчик 2 вместо 1, когда выполняется GetRecentMsgs (), что странно.Вот отладочный журнал ниже.
Received values for ChatIds.
Chat Room Id's : -LOEgQUGcG4P2jMRmO22
CHATLIST COUNT(ChatidRetreive) : 1
Received values for RecenttMessages.
CHATLIST COUNT(ChatidRetreive) : 2
Received values for RecenttMessages.
CHATLIST COUNT(ChatidRetreive) : 2
Created Recent Message : hello
CHATLIST COUNT(AfterCreatedRMbutton) : 2
Created Recent Message : CfXVOi8XFib4q4X1q02pAnoNsek2
CHATLIST COUNT(AfterCreatedRMbutton) : 2
Код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;
public class MessagingHandler : MonoBehaviour {
private string currentID;
private string chatingWithID;
private string chatID;
public FirebaseMethods fh;
public GameObject Button_Template;
public GameObject RecentMsg_Template;
List<string> chatIds = new List<string>();
ArrayList recentMsgs = new ArrayList();
ArrayList messages = new ArrayList();
private GameObject[] recent_msgs;
private GameObject[] msgs;
DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
public void InitializeMsgHandler()
{
currentID = fh.userID;
chatIds.Clear();
chatIds.Add("Firebase");
messages.Clear();
messages.Add("Firebase");
msgs = new GameObject[1];
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
// Initialize the Firebase database:
protected virtual void InitializeFirebase()
{
FirebaseApp app = FirebaseApp.DefaultInstance;
// NOTE: You'll need to replace this url with your Firebase App's database
// path in order for the database connection to work correctly in editor.
app.SetEditorDatabaseUrl(FirebaseGlobals.dbUrl);
if (app.Options.DatabaseUrl != null)
app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
StartListener();
}
protected void StartListener()
{
LoadRecentMessages();
}
private void LoadRecentMessages()
{
FirebaseDatabase.DefaultInstance
.GetReference("chat")
.Child("users_chat_info")
.Child(currentID)
.ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
if (e2.DatabaseError != null)
{
Debug.LogError(e2.DatabaseError.Message);
return;
}
Debug.Log("Received values for ChatIds.");
string title = chatIds[0].ToString();
chatIds.Clear();
chatIds.Add(title);
//Debug.Log(recentMsgs.ToString());
if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0)
{
foreach (var childSnapshot in e2.Snapshot.Children)
{
if (childSnapshot == null || childSnapshot.Value == null)
{
Debug.LogError("Bad data in sample. Did you forget to call SetEditorDatabaseUrl with your project id?");
break;
}
else
{
Debug.Log("Chat Room Id's : " + childSnapshot.Child("chat_id").Value.ToString());
Debug.Log("CHATLIST COUNT(ChatidRetreive) : " + chatIds.Count);
//chatIds.Insert(1, childSnapshot.Child("chat_id").Value.ToString());
chatIds.Add(childSnapshot.Child("chat_id").Value.ToString());
}
}
}
GetRecentMsgs();
};
}
private void GetRecentMsgs()
{
for (int i = 0; i < chatIds.Count; i++)
{
FirebaseDatabase.DefaultInstance
.GetReference("chat")
.Child("chat_rooms")
.Child(chatIds[i])
.Child("m_recent")
.ValueChanged += (object sender2, ValueChangedEventArgs e2) =>
{
if (e2.DatabaseError != null)
{
Debug.LogError(e2.DatabaseError.Message);
return;
}
Debug.Log("Received values for RecenttMessages.");
Debug.Log("CHATLIST COUNT(ChatidRetreive) : " + chatIds.Count);
if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0)
{
foreach (var childSnapshot in e2.Snapshot.Children)
{
if (childSnapshot == null || childSnapshot.Value == null)
{
Debug.LogError("Bad data in sample. Did you forget to call SetEditorDatabaseUrl with your project id?");
break;
}
else
{
Debug.Log("Created Recent Message : " + childSnapshot.Value.ToString());
GameObject go = Instantiate(RecentMsg_Template) as GameObject;
go.SetActive(true);
Msg TB = go.GetComponent<Msg>();
go.transform.SetParent(RecentMsg_Template.transform.parent);
Debug.Log("CHATLIST COUNT(AfterCreatedRMbutton) : " + chatIds.Count);
}
}
}
};
}
}
}