Apparently, the issue was caused by not instantiating the assets from the main thread.
I made a custom implementation for forcing the method to run in the main thread, and it is now solved.
This is the class that I created to force a method to run in the main thread:
using System.Collections.Generic;
using UnityEngine;
public class UnityMainThreadDispatcher : MonoBehaviour
{
public static UnityMainThreadDispatcher _instance;
private static Queue<System.Action> _actionQueue = new
Queue<System.Action>();
private void Awake()
{
if (!Application.isBatchMode)
{
Destroy(this.gameObject);
}
if (_instance != null)
{
Destroy(gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
}
void Update()
{
lock (_actionQueue)
{
while (_actionQueue.Count > 0)
{
_actionQueue.Dequeue().Invoke();
}
}
}
public void ExecuteOnMainThread(System.Action action)
{
lock (_actionQueue)
{
_actionQueue.Enqueue(action);
}
}
}
Then, for all the code that I want to force to the main thread, I use this:
UnityMainThreadDispatcher._instance.ExecuteOnMainThread(async () =>
{
// Enter code here
});