Game Development Reference
In-Depth Information
the caches also prevent you from loading the same resource twice. Whether you create
a single sprite or a thousand sprites using the same texture, the texture will only be
loaded and stored in memory once.
There are a few more (but rarely used) singleton classes in cocos2d:
CCConfiguration* config = [CCConfiguration sharedConfiguration];
CCProfiler* profiler = [CCProfiler sharedProfiler];
To complete the list, the CocosDenshion audio engine also provides two singleton
classes to the CDAudioManager and its easier-to-use cousin SimpleAudi-
oEngine :
CDAudioManager* sharedManager = [CDAudioManager sharedManager];
SimpleAudioEngine* sharedEngine = [SimpleAudioEngine sharedEngine];
The upside of a singleton is that it can be used anywhere by any class at any time. It
acts almost like a global class, much like global variables. Singletons are very useful if
you have a combination of data and methods you need to use in many different places.
Caching and audio are good examples of this, because any of your classes—whether
the player, an enemy, a menu button, or a cutscene—might want to play a sound effect
or change the background music. So it makes a lot of sense to use a singleton for play-
ing audio. Likewise, if you have global game stats—perhaps the size of the player's
army and each platoon's number of troops—you might want to store that information
in a singleton so you can carry it over from one level to another.
Implementing a singleton is straightforward, as Listing 3-2 shows. This code imple-
ments the class MyManager as a singleton with minimal code. The sharedMan-
ager static method grants access to the single instance of MyManager . The first time
the sharedManager method runs, the sharedManager instance is allocated and
initialized; from then on the existing instance is returned.
Listing 3-2. Implementing the Exemplary Class MyManager as a Singleton
static MyManager *sharedManager = nil;
+(MyManager*) sharedManager
{
 
 
Search Nedrilad ::




Custom Search