Search code examples
c#storagetexture2d

How to store Texture2D in a listDictionary in C#?


I am having problems with retrieving a texture2D from a listDictionary.

This is my LoadGraphics Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;

namespace Space_Game
{
    public static class LoadGraphics
    {
        //global variable
        public static ListDictionary _blue_turret_hull;

        public static void LoadContent(ContentManager contentManager)
        {
            //loads all the graphics/sprites
            _blue_turret_hull = new ListDictionary();
            _blue_turret_hull.Add("graphic", contentManager.Load<Texture2D>("Graphics/Team Blue/Turret hull spritesheet"));
            _blue_turret_hull.Add("rows", 1);
            _blue_turret_hull.Add("columns", 11);
        }
    }
}

This is the Turret class the should retrieve the Texture2D:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Space_Game
{
    class Turret_hull:GameObject
    {
        public Turret_hull(Game game, String team)
            : base(game)
        {
            if(team == "blue") { _texture = LoadGraphics._blue_turret_hull["graphic"];      }
        }
    }
}

Only here it gives the following error:

Cannot implicitly convert type 'object' to 'Microsoft.Xna.Framework.Graphics.Texture2D'. An explicit conversion exists (are you missing a cast?)

I know there is a problem regarding the fact that I stored it in a listDictionary. I did that, because that way I could retrieve all necessary info at once. How else should I do this?

Thanks in Advance,

Mark Dijkema


Solution

  • Probably a better way to achieve what you want is to define a new class with 3 properties and use this to retrieve the info you need to pass around:

    public class TurretHullInfo
    {
        Texture2D Graphic { get; set; }
        int Rows { get; set; }
        int Columns { get; set; }
    }
    
    public static class LoadGraphics
    {
        //global variable
        public static TurretHullInfo _blue_turret_hull;
    
        public static void LoadContent(ContentManager contentManager)
        {
            //loads all the graphics/sprites
            _blue_turret_hull = new TurretHull();
            _blue_turret_hull.Graphic = contentManager.Load<Texture2D>("Graphics/Team Blue/Turret hull spritesheet");
            _blue_turret_hull.Rows = 1;
            _blue_turret_hull.Columns = 11;
        }
    }
    
    class Turret_hull : GameObject
    {
        public Turret_hull(Game game, String team)
            : base(game)
        {
            if(team == "blue")
                _texture = LoadGraphics._blue_turret_hull.Graphic;     
        }
    }