Here's a class to manage textures for c#. No bells, no whistles.
public class ResourceManager
{ //Our base texture.. Texture sfmlTexture
; //Resource collection(s).. protected Dictionary
<string, Texture
> textureCache
; //Don't create.. private ResourceManager
() { textureCache
= new Dictionary
<string, Texture
>(); } //Create a static reference.. private static ResourceManager manager
= null; //Return an instance of it on demand to create resources... public static ResourceManager ReturnInstance
() { if (manager
== null) { manager
= new ResourceManager
(); } return manager
; } public Texture CreateTextureResource
(string filename
) { //Make sure we havent created the resource already... if (textureCache
.ContainsKey(filename
)) { //We already created it so, return it... return textureCache
[filename
] as Texture
; } else { //We havent created it, do so and add it to the collection... sfmlTexture
= new Texture
(filename
); textureCache
.Add(filename, sfmlTexture
); //Return the texture... return textureCache
[filename
] as Texture
; } } //Call this explicitly as you shut down the application to dispose of the textures.. public void CleanUpTextures
() { //Dispose all textures.. foreach (Texture t
in textureCache
.Values) { if (t
!= null) { t
.Dispose(); } } //Clear the cache.. textureCache
.Clear(); } } To use this you need to call it directly from the TYPE such as:
MyGameObject.Texture = ResourceManager.ReturnInstance().CreateTextureResource("Foo.png");
In essence this class is a singleton. Seeing as the video card only needs one copy of a bitmap to render to multiple entities creating textures using a method like this ensures there is only ONE of each bitmap ever kept in memory.