I'm trying to create a scrollview with buttons where the "titulo" field is retrieved from Firebase Realtime Database. I have got to read the Firebase json but I cannot apply the names in the buttons when iterate and no button appears in the scrollview.
Can anybody help me please? Thank you in advance.
This is my code:
FirebaseDatabase.DefaultInstance
.GetReference("Flash")
.GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.Log("Error al leer la Base de Datos de Firebase");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
Debug.Log("Base de datos: " + snapshot.GetRawJsonValue());
foreach (DataSnapshot evento in snapshot.Children)
{
string titulo = (string)evento.Child("titulo").Value;
lat = float.Parse(evento.Child("lat").Value.ToString());
lon = float.Parse(evento.Child("lon").Value.ToString());
string descripcion = (string)evento.Child("descripcion").Value;
Debug.Log("Titulo: " + titulo);
Debug.Log("Latitud: " + lat);
Debug.Log("Longitud: " + lon);
Debug.Log("Descripcion: " + descripcion);
GameObject go = Instantiate(Button_Template) as GameObject;
go.SetActive(true);
BC_TButton_FLASH TB = go.GetComponent<BC_TButton_FLASH>();
TB.SetTitulo(titulo);
go.transform.SetParent(Button_Template.transform.parent);
go.transform.localScale = new Vector3(1, 1, 1);
}
}
});
And:
public class BC_TButton_FLASH : MonoBehaviour {
private string Titulo;
private float Lat;
private float Lon;
private string Descripcion;
public Text ButtonText_Titulo;
public BC_TData_WS_FLASH ScrollView;
public void SetTitulo(string titulo)
{
Titulo = titulo;
ButtonText_Titulo.text = titulo;
}
}
And the json is like this:
{
"Flash" : [ {
"descripcion" : "aaaaa",
"lat" : 12.32145,
"lon" : 6.789,
"titulo" : "a1"
}, {
"descripcion" : "bbbbb",
"lat" : 21.41254,
"lon" : -2.4396,
"titulo" : "a2"
}, {
"descripcion" : "ccccc",
"lat" : 42.3434,
"lon" : 345345,
"titulo" : "a3"
} ]
}
Your problem is multithreading.
Most of the Unity API can only be used in the Unity main thread. In particular anything that immediately requires or influences the current scene (so the exception are pure mathematical structs like calculations with Vector3, Plane, Quaternion etc)
Task.ContinueWith is NOT continuing with the execution in the main thread
Creates a continuation that executes asynchronously when the target Task completes.
Therefore specifically for Unity Firebase provides the TaskExtentsions with ContinueWithOnMainThread
Returns a Task which completes once the given task is complete and the given continuation function is called from the main thread in Unity.
so you should use
FirebaseDatabase.DefaultInstance
.GetReference("Flash")
.GetValueAsync().ContinueWithOnMainThread(task =>
{
...