Search code examples
c#monogame

How do I properly get all textures within a folder withing Monogame?


I'm pretty new to C# and Monogame, I'm trying to make a SpriteLoop functionality where you can play sprites, by giving an array of Sprites from a folder of textures. I am trying the code given below, however when I try to draw the sprites using spriteBatch.Draw like this:

spriteBatch.Begin();
foreach(Texture2D texture in spriteLoop)
    spriteBatch.Draw(texture, new Vector2(0,0), Color.White);
spriteBatch.End();
base.Draw(gameTime);

nothing happens, I made sure to include image files in the folder, and they even show up when I console log them. Please help me find out what is specifically wrong in the code. Any help is appreciated. Thanks!

public static class TextureContent
{
    public static List<Texture2D> TexturesFromFolder(this ContentManager contentManager, GraphicsDevice graphics, string contentFolder)
    {
        //System.Console.WriteLine("./Content/"+contentFolder);
        DirectoryInfo dir = new DirectoryInfo(contentManager.RootDirectory+"/"+contentFolder);
        if(!dir.Exists)
            throw new DirectoryNotFoundException();
        List<Texture2D> result = new List<Texture2D>();

        FileInfo[] files = dir.GetFiles("*.*");
        foreach(FileInfo file in files)
        {
            string key = Path.GetFileName(file.Name);
            System.Console.WriteLine(key);
            //result.Add(contentManager.Load<Texture2D>(contentFolder + "/" + key));
            FileStream fileStream = new FileStream(contentManager.RootDirectory+"/"+contentFolder+"/"+key, FileMode.Open);
            Texture2D spr = Texture2D.FromStream(graphics, fileStream);
        }
        return result;
    }
}

Solution

  • If you check the end of your foreach loop in the TexturesFromFolder method, you can see that you are indeed loading the texture from the stream, but you never actually add it to the result list. Meaning you always return an empty list.