有效保持内容

时间:2014-07-26 19:22:52

标签: c# xna

所以我有这个名为TypingKeyboard的班级。它是一个在屏幕上绘制字符串的类,好像它是由某人键入的,带有声音。我将它用于很多事情,例如主菜单,积分和游戏本身。

class TypingKeyboard
{
    SoundEffect foo;

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

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

为了听到声音,您需要加载声音并存储它们。对于我所拥有的课程的每个实例都会发生这种情况。

因此,每次创建此类时,都需要调用LoadContent并将SoundEffect加载到RAM中。这不是很有效,因为我总是使用相同的声音。

Illustration of the problem

有没有办法可以创建一个你需要制作一次实例的类,然后可以在任何地方调用声音#34;我想要吗?

像这样:

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

2 个答案:

答案 0 :(得分:1)

使用lazy singleton模式:

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
}

更多here

答案 1 :(得分:0)

您可以将ContentManager传递给声音类(或您想要的任何类)的构造函数方法,并在类本身内加载声音:

class Sounds
{
    SoundEffect sound;
    public Sounds(ContentManager content)
    {
        sound = content.Load<SoundEffect>("wavFileName");
    }

    public void PlaySound()
    {
    sound.Play();
    }
}

要选择多种音效,您可以在声音类中加载更多声音效果,并在构造函数方法中传入一个int,同时使用基于int的if语句来确定播放哪种声音。

相关问题