Andreea Ogledean
Andreea Ogledean

Reputation: 21

Load all existent files (sprites) from Application.persistentDataPath? Unity

In my game, you can take screenshots of the world, which are saved in Application.persistentDataPath. I want to make a gallery where you can then see all these screenshots. Because you need to write to the file, I can't use Resources folder or Application.streamingAssetsPath. I could read the files one sprite at a time, using the name, but that's not really practical. So how could I load all files and add them to an array or list? I basically need the equivalent of Resources.LoadAll(). Does anyone know how to achieve this?

Upvotes: 2

Views: 3677

Answers (1)

derHugo
derHugo

Reputation: 90852

You can use Directory.GetFiles(string,string) to return all filepaths in the persistentData folder e.g. by file extension ("*.jpg")

Then you can use e.g. UnityWebRequestTexture.GetTexture also on local file paths and load assets from the persistent data path like

public Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();

private void Start()
{
    var fileNames = Directory.GetFiles(Application.persistentDataPath, "*.jpg");

    foreach(var fileName in fileNames)
    {
       StartCoroutine (LoadFile(fileName));
    }
}

private IEnumerator LoadFile(string filePath)
{
    using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(filePath))
    {
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log(uwr.error);
        }
        else
        {
            // Get downloaded asset bundle
            var texture = DownloadHandlerTexture.GetContent(uwr);

            // Something with the texture e.g.
            // store it to later access it by fileName
            var fileName = Path.GetFileName(filePath);
            textures[fileName] = texture;
        }
    }
}

Upvotes: 1

Related Questions