Unity: Why downloading a text asset from internet doesn't work?

68 views Asked by At

I tried to use a coroutine to download a get a text by UnityWebRequest.Get(url);

In the NetworkManager Class, I have these two exactly identical Coroutines but in different name:

public static IEnumerator DownloadTextCoroutine(string url, Action<string> callback)
    {
        List<word> newList = new List<word>();
        UnityWebRequest web = UnityWebRequest.Get(url);
        yield return web.SendWebRequest();

        if (web.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(web.error);
        }
        else
        {
            string Unprocessed = web.downloadHandler.text;
            callback?.Invoke(Unprocessed);
        }
    }

In the GameManager Class, I tried to run the coroutine and pass the text assests requested to a method initPlayerData(string A, string B), (i.e. this method is totally fine, so no worries about it). So In awake(), I run the coroutine. But it turns out the text assests are not downloaded.

 public void Awake()
        {
            if (instance == null)
            {
                instance = this;
                DontDestroyOnLoad(this.gameObject);
            }
            else
            {
                Destroy(this.gameObject);
            }

            Debug.Log(FirstTimeChecking.checkIsFirstTime());

            if (FirstTimeChecking.checkIsFirstTime())
            {
                StartCoroutine(NetworkManager.DownloadTextCoroutine("https://xxx/words.txt", result =>
                {
                    words = result;
                    isWordsDownloaded = true;
                }));

                StartCoroutine(NetworkManager.DownloadIdiomCoroutine("https://xxx/idioms.txt", result =>
                {
                    idioms = result;
                    isIdiomsDownloaded = true;
                }));

                StartCoroutine(WaitForDownloads());
            }
            else
            {
                playerData = playerDataLoader.playerData;
            }
        }

        private IEnumerator WaitForDownloads()
        {
            // Wait until both downloads have completed
            while (!isWordsDownloaded || !isIdiomsDownloaded)
            {
                yield return null;
            }

            // Run code after the downloads have completed
            initPlayerData(words, idioms);
        }

I expecct I can access 2 text assests and store them into a variable and pass it to initPlayerData(words, idioms); and the game shall run well.

I have tried this way and other many ways. If I put the coroutine in initPlayerData() [original], where there are some loops to handle the data, works. So I decided to seperate the Requesting Text process and the data process, i.e. initPlayerData(words, idioms);.

Thank you so much

0

There are 0 answers