Reputation: 1067
What I want to do is to Load()
a sound effect in XNA using the Content Manager and automatically create a instance to control playback. When the sound is no longer needed, I was wondering how to properly Unload()
it from memory?
Furthermore, I was wondering if Unload()
is even needed. When I call Load()
twice, does the second call properly free the memory of the first call? I would guess that the C# garbage collector automatically disposes the old effect and instance as they are being overwritten by the second call. Is this correct?
These are the parameters in my custom MySoundEffect
class:
// Has sound effect been loaded?
bool loaded;
// Store our SoundEffect resource
SoundEffect effect;
// Instance of our SoundEffect to control playback
SoundEffectInstance instance;
This method is loading the sound.
public void Load(String location)
{
effect = Content.Load<SoundEffect>(location);
if (effect != null) loaded = true;
else
{
Error.Happened("Loading of sound effect " + location + " failed.");
return;
}
// Create instance
instance = effect.CreateInstance();
}
This is called when the sound is no longer needed:
public void Unload()
{
loaded = false;
instance.Dispose();
effect.Dispose();
}
Upvotes: 1
Views: 369
Reputation: 4213
If you want to unload a single sound you can call Dispose
method, but it's important that you never need it again, or you'll receive an excepion of disposed element.
You can create a second ContentManager
where you can load the sounds that you use only one time, and then Unload
it.
To answer to your second question, you are wrong:
Each instance of ContentManager will only load any given resource once. The second time you ask for a resource, it will return the same instance that it returned last time.
To do this, ContentManager maintains a list of all the content it has loaded internally. This list prevents the garbage collector from cleaning up those resources - even if you are not using them.
Upvotes: 1