D
D
Danil Chekalin2018-01-16 16:16:52
Mono
Danil Chekalin, 2018-01-16 16:16:52

How to implement implement resource loader from web in Unity?

I have two tasks:
1. I want to download a text file from the web, but I don't understand how to write a class that will have a static method that takes a url and eventually returns the downloaded content. Namely, it is not clear to me how to do this with IEnumerator, considering that it does not return anything when it is executed.
2. I would like to load during game initialization. The test file will contain configs for everything (player speed, etc.). And as far as I understand, IEnumerator execution is not a blocking operation. How to implement?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2018-01-16
@dakiesse

As for static, it’s up to you to decide, but in general it’s easiest to pass a callback to coroutines:

using UnityEngine;
using System;
using System.Collections;

public class Example : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine(DownloadFile("url", text => DeserializeConfig(text, () => Debug.Log("Done"))));
    }

    private IEnumerator DownloadFile(string url, Action<string> onComplete)
    {
        using (WWW www = new WWW(url))
        {
            yield return www;
            onComplete(www.text);
        }
    }

    private void DeserializeConfig(string text, Action onComplete)
    {
        Debug.Log(text);
        onComplete();
    }
}

This scheme builds a ladder of nested delegates very quickly, but at least it gets the job done. The best solution would be to use promises or UniRx , then it will be easier to manage the flow.
Blocking IEnumerator depends on the severity of operations between yields, coroutines are executed in the same thread, they just allow you to spread code execution between frames.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question