Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!


1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


Dictionary of Dictionaries based on Type


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 dechorus   Members   -  Reputation: 120

Like
0Likes
Like

Posted 03 June 2013 - 06:48 PM

Hey guys. I'm working in XNA.

 

I'm basically trying to have a Data/Asset Manager class that holds everything that's loaded in by the ContentManager.

 

I'm trying to have a property that's essentially something along the lines of

 

 

Dictionary<T, Dictionary<string, T>> listOfObjects;

 

 

My hope is to be able to get objects doing something like

 

 

Texture2D texture = listOfObjects<Texture2D>("nameOfTexture");

SpriteFont font = listOfObjects<SpriteFont>("nameOfFont");

// etc. 

 

 

Any help and / or suggestions? Thank you so much in advance smile.png


Edited by dechorus, 03 June 2013 - 06:49 PM.


Sponsor:

#2 Ravyne   GDNet+   -  Reputation: 10234

Like
0Likes
Like

Posted 03 June 2013 - 07:05 PM

I'm not super familiar with .Net's Dictionary type, as its been awhile since I've used it, but while its entirely possible to have a dictionary of dictionaries, I don't think that your intention can be expressed in the way you are attempting because it would make the value-type dependent upon the index type, unless .Net generics work even more differently than C++ templates than I think they do.

 

More to the point though, why do you want to be able to determine the appropriate list of homogenous objects from the type of its value? In practice, one needs to statically know the value type anyhow, in order to store or reference it, so I don't get how this extra contortion is meant to be useful. In other words, whats wrong with listOfTextures("nameOfTexture"), and listOfFonts(""nameOfFont)?

 

There are ways to achieve exactly what your post lays out, but you sacrifice some type safety in doing so, which is generally frowned upon if reasonable solutions avoid it.



#3 dechorus   Members   -  Reputation: 120

Like
0Likes
Like

Posted 03 June 2013 - 07:14 PM

My initial implementation is in fact having multiple dictionaries for each type, which is absolutely fine.

 

I suppose the reason I wanted it this way was so that the class could be generic enough to be used across projects.

 

If I required a dictionary of objects using a class that was specific to a particular game, such as a Level class, then the list would be generic enough for me to Add and Get levels, as opposed to adding a new dictionary for Levels which would be specific to a game project.

 

Does that make sense? 

 

Thank you for your response!



#4 Nypyren   Crossbones+   -  Reputation: 6471

Like
0Likes
Like

Posted 03 June 2013 - 07:32 PM

T itself needs to be a concrete type for the case you're using it in, for example:
 
public static class AssetManager
{
  public static Dictionary<string,Texture2D> Textures;
  public static Dictionary<string,SpriteFont> Fonts;
}
 
elsewhere:
{
  var texture = AssetManager.Textures["nameOfTexture"];
}
 
(my use of static here is optional and not required if you want an instance-based AssetManager)


You can put dictionaries of different types inside one big dictionary, but it's uglier than it needs to be:
public static class AssetManager
{
  static Dictionary<Type,object> dict;

  T GetAssetByType<T>(string key) where T:class
  {
    object o;
    if (dict.TryGetValue(typeof(T), out o))
    {
      var nestedDict = o as Dictionary<string,T>;
      if (nestedDict != null)
        return nestedDict[key];
    }    

    return null;
  }
}

elsewhere:
{
  var texture = AssetManager.GetAssetByType<Texture2D>("nameOfTexture");
}
Another option is to just have the AssetManager itself be generic. Static generics get a separate static definition per generic type.
public static class AssetManager<T> where T:class // or the base class of XNA assets, if you want
{
  public static Dictionary<string,T> Assets;
}

elsewhere:
{
  var texture = AssetManager<Texture2D>.Assets["nameOfTexture"];
}

Edited by Nypyren, 03 June 2013 - 07:47 PM.


#5 phil_t   Crossbones+   -  Reputation: 5144

Like
0Likes
Like

Posted 03 June 2013 - 07:57 PM

What's your end goal exactly?

 

My hope is to be able to get objects doing something like
 
 
Texture2D texture = listOfObjects<Texture2D>("nameOfTexture");

SpriteFont font = listOfObjects<SpriteFont>("nameOfFont");

// etc. 

 

That's exactly what XNA's ContentManager does.

 

Texture2D texture = Content.Load<Texture2D>("nameOfTexture");

SpriteFont font = Content.Load<SpriteFont>("nameOfFont");

 

Why not just use that?



#6 Ravyne   GDNet+   -  Reputation: 10234

Like
0Likes
Like

Posted 03 June 2013 - 07:58 PM

I would propose that you are attempting to encapsulate asset management at the wrong level by putting all asset types into one container, and that encapsulating at the level of individual resource types, as in your original solution, is indeed the correct course of action. At some point, your game needs to know that its requesting a level, loading a level, getting a level in return. Your original solution is already generic enough to take any asset type (or should be), albeit in separate containers that may be game specific, so its eminently re-usable for textures, levels, or anything else.

 

Your game already needs to know that either:

  • I ask a container to tell me about another container that holds levels, then I ask that container about the level I want.

-or-

  • I have a container of textures, levels, and other things, I know which one I'm dealing with now, I can ask the right container about the level I want directly.

 

Again, there are ways to implement your alternative proposal by eschewing some type safety -- you can probably even do it in a way where all the type un-safety is internal to the asset manager class -- but you will still, at some level, be effectively instantiating a set of functionality specific to an asset type that is separate from like functionality of other asset types. This alternative implementation becomes nothing more than a logical firewall between you and the implementation you think you'll be avoiding.

 

Setting that aside, there are benefits to keeping asset managers of different types separate -- for example, your caching strategy for sounds, textures, and levels may all be very different from one another. Putting them all in one super-container makes using different strategies for different types not only more difficult, but creates an unnecessary level of decoupling (usually, decoupling is a good thing, but here it would be 1 step too far removed).



#7 dechorus   Members   -  Reputation: 120

Like
0Likes
Like

Posted 03 June 2013 - 08:50 PM

What's your end goal exactly?

 

 

My hope is to be able to get objects doing something like
 
 
Texture2D texture = listOfObjects<Texture2D>("nameOfTexture");

SpriteFont font = listOfObjects<SpriteFont>("nameOfFont");

// etc. 

 

That's exactly what XNA's ContentManager does.

 

Texture2D texture = Content.Load<Texture2D>("nameOfTexture");

SpriteFont font = Content.Load<SpriteFont>("nameOfFont");

 

Why not just use that?

 

The ContentManager is used to Load objects, not get them once they've been loaded. I don't think I'd be creating new variables for each and every texture and so on. A Dictionary seems more appropriate.

 

As for the generic solution I was after, I've come up with this:

 

        Dictionary<Type, object> dict;

        public void Add<T>(string key, T value)
        {
            Type type = typeof(T);
            bool dictContainsKey = dict.ContainsKey(type);

            if (!dictContainsKey)
                dict.Add(type, new Dictionary<string, T>());

            Dictionary<string, T> nestedDict = dict[type] as Dictionary<string, T>;

            if (nestedDict.ContainsKey(key))
                nestedDict[key] = value;
            else
                nestedDict.Add(key, value);
        }

        public T Get<T>(string key)
        {
            Type type = typeof(T);
            bool dictContainsKey = dict.ContainsKey(type);

            if (!dictContainsKey)
                return default(T);

            Dictionary<string, T> nestedDict = dict[type] as Dictionary<string, T>;

            if (nestedDict.ContainsKey(key))
                return nestedDict[key];
            else
                return default(T);
        }

What are your thoughts - is this a bad / unnecessary implementation?

 

Admittedly it's a little messy, and probably unnecessary. For whatever reason I felt a single Dictionary with all assets is the way to go. My plan was to then write getters and setters and so on for accessing specific types, such as GetTexture(string key) { return // ... gets Texture2D from nested dictionary in dict }

 

Anyway, I guess having Dictionaries for each type seems to be a more suitable and cleaner solution.

 

Thanks everybody for your input.



#8 phil_t   Crossbones+   -  Reputation: 5144

Like
5Likes
Like

Posted 03 June 2013 - 08:56 PM

The ContentManager is used to Load objects, not get them once they've been loaded. I don't think I'd be creating new variables for each and every texture and so on. A Dictionary seems more appropriate.

 

It's used for both. It loads resources and (internally) puts them in a dictionary so they can be quickly retrieved next time.

 

You're just re-implementing what already exists. (fyi, you might want to use dotPeek to see how ContentManager is implemented).


Edited by phil_t, 03 June 2013 - 08:58 PM.


#9 Andy474   Members   -  Reputation: 690

Like
0Likes
Like

Posted 04 June 2013 - 02:06 AM

Personally i use somthing like this:

 

 

public Dictionary<string, object> _AssetDictionary;


public void LoadAssets()
{
    _AssetDictionary = new Dictionary<string, object>();
    _AssetDictionary.Add("FONT_MENUFONT", LoadSpritefont(MenuFont));
    _AssetDictionary.Add("ASSET_AWESOMETEXTURE", LoadTexture(MenuFont));
}
public T Get<T> GetAsset(string name)
{
    return (T)_AssetDictionary[name];
}

//Reference with
GetAsset<Texture2D>("ASSET_AWESOMETEXTURE");

ofc string can be replaced with anything, even object :P so you have have it stored by different enum values.

 

There are many ways to expand on this, but strings suffice for most things.


Edited by Andy474, 04 June 2013 - 02:07 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS