Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to have a music on/off setting objective-c
    text
    copied!<p>I am making a simple game in cocos2d and I wanted to make a simple button toggle to keep sounds on or off. This is what I did so far...</p> <p>In my <code>.h</code>:</p> <pre><code>CCMenuItemImage *sound; CCMenu *menu2; </code></pre> <p>In my <code>init</code>:</p> <pre><code>[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"musicon"]; // Sound Buttons sound = [CCMenuItemImage itemWithNormalImage:@"music.png" selectedImage:@"music.png" target:self selector:@selector(turnOffSound)]; sound.scale = 1.1; menu2 = [CCMenu menuWithItems:sound, nil]; menu2.position = ccp(screenCenter.x - 33,screenCenter.y / 5); [self addChild:menu2]; </code></pre> <p>And then my <code>turnOffSound</code> and <code>turnOnSound</code> method:</p> <pre><code>-(void) turnOnSound { [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"musicon"]; [self removeChild:sound cleanup:YES]; [self removeChild:menu2 cleanup:YES]; sound = [CCMenuItemImage itemWithNormalImage:@"music.png" selectedImage:@"music.png" target:self selector:@selector(turnOffSound)]; sound.scale = 1.1; menu2 = [CCMenu menuWithItems:sound, nil]; menu2.position = ccp(screenCenter.x - 33,screenCenter.y / 5); [self addChild:menu2]; } -(void) turnOffSound { [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"musicon"]; [self removeChild:sound cleanup:YES]; [self removeChild:menu2 cleanup:YES]; sound = [CCMenuItemImage itemWithNormalImage:@"music-not.png" selectedImage:@"music-not.png" target:self selector:@selector(turnOnSound)]; sound.scale = 1.1; menu2 = [CCMenu menuWithItems:sound, nil]; menu2.position = ccp(screenCenter.x - 33,screenCenter.y / 5); [self addChild:menu2]; } </code></pre> <p>Right now, the toggle works but only on this screen (this is the title screen), because when I go to another screen, then go back to the title screen, the BOOL is being set to true again. Do you know how I can make it not reset again? Any help is appreciated, thank you!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload