0

Newbie to iOS and Cocos2d ( 2.x )

Ok I want to create a Menu Object and call it from each new Scene.

Example:

  • Scene1, add menu
  • Scene2, add same menu as on Scene1

I've only seen how to initialize the CCMenu when you init the Layer itself. you build the items and then add them to the CCMenu and so on.

How can I initialize the CCMenu once and then just add it to what ever scene I happen to be viewing? So if I'm viewing Scene1 or Scene2 it's still the same menu.

Does this make sense?

Phill Pafford
  • 83,471
  • 91
  • 263
  • 383

1 Answers1

1

You'll need a different instance of the menu for each scene, so technically speaking, you'll need to initialize it once per scene.

But I think you're asking "how can I write the code once and then reuse that code in each scene." You'll want to create some sort of CC Object that you can reuse. This could be a subclass of a CCMenu, CCLayer, or whatever suits the purpose best. So you may try something like:

@interface MyMenuLayer : CCLayer {
  CCMenu *myMenu;
}
@end

Then in the .m file, set up your menu however you like. When you want to include this in Scene1:

MyMenuLayer *menu = [MyMenuLayer node];
[self addChild:menu];

You can use the exact same code in Scene2.

(You could just extend CCMenu instead of CCLayer, but I personally prefer to work with Layers instead of Menus. It's a matter of personal choice.)

It's hard to give a very definitive answer with the information in your question, but I hope this gets you set off on the right path.

  • Thanks, I think this is what I was asking. So when creating the CC Object as a CCLayer, then I can declare the menu there and then just include it in the Scenes, correct? What is the benefit from making this a CCLayer? I think I understand why I'm just wanting to confirm. +1 and thanks – Phill Pafford Dec 11 '12 at 13:23
  • You are correct; just create the menu inside your custom object and then include that in whatever other node you want (using addChild). The benefit to making this a sub of CCLayer versus CCMenu? Not much. It's just a matter of personal preference. In case you wanted to add something like a title to your menu, it would make more sense to include that in a CCLayer than in a CCMenu. (I believe it would work for a CCMenu.) – So Much Drama Studios Dec 11 '12 at 15:42
  • One other quick note: I should have specified that you're looking to subclass some sort of CCNode, not a CCObject. But the CCMenu and CCLayer are correct examples. – So Much Drama Studios Dec 11 '12 at 16:10
  • Ah, Thanks again. Will try this out later tonight – Phill Pafford Dec 11 '12 at 17:57