Search code examples
c#xna

Hold content efficiently


So I have got this class called TypingKeyboard. It's a class that draws a string on the screen as if it is typed by someone, with sounds. I use this for many things, for example in the main menu, credits and the game itself.

class TypingKeyboard
{
    SoundEffect foo;

    public TypingKeyboard(string text, int intervalBetweenKeys, blah blah blah){}

    public void LoadContent(ContentManager content)
    {
        foo = Content.Load<SoundEffect>("keysoundthinggy");
    }
}

In order to hear sounds you need to load the sounds, and store them. This happens for every instance of the class I have.

So every time you make this class, you need to call LoadContent and it loads the SoundEffect to the RAM. This is not very efficient since I always use the same sounds.

Illustration of the problem

Is there a way that I can create a class that you need to make an instance of once and then can call the sounds from "anywhere" I want?

Like this:

// I need to play the sound!
TypingKeyboardData.Foo.Play();

Solution

  • Use the lazy singleton pattern:

    public class TypingKeyboardData
    {
        private static readonly Lazy<TypingKeyboardData> _instance
            = new Lazy<TypingKeyboardData>(() => new TypingKeyboardData());
        // private to prevent direct instantiation.
        private TypingKeyboardData()
        {
        }
        // accessor for instance
        public static TypingKeyboardData Instance
        {
            get
            {
                return _instance.Value;
            }
        }
    
        // Add all required instance methods below
    }
    

    More here.