0

i am new on cocos2d, I have

int score;//default 0

I am increasing the score but when switch scene, score is going to be 0 again. How can i keep the score when i switch the scene?

Sorry for my bad english.

Best Regards. Thanks for your advice.

Kirdok
  • 1,904
  • 2
  • 22
  • 27

2 Answers2

0

You are storing a score in a scene - perhaps this would be better stored in a single location that all of your scenes can access? After all, your scene should be concerning itself with managing your views and user interaction rather than game logic.

There are many approaches for this: will there only be one game happening at once? If so, perhaps a singleton would be a good way to manage this data.

If not, you will need a reference to the score in each scene (that is to say, each scene would need a public variable that the previous scene can transfer the score value to before presenting).

davbryn
  • 7,156
  • 2
  • 24
  • 47
  • It worked, thank you very much, By the way,i learned to use singleton.Thanks again – Kirdok Nov 16 '13 at 17:01
  • 1
    And there goes another beginner using singletons ... sigh. – CodeSmile Nov 16 '13 at 20:05
  • @LearnCocos2D I hope there are no singletons in Kobold2D - I'd hate to see another beginner fall foul of a perfectly reasonable design decision - NSUserDefaults to store an in-game score?!? And you sell this information? You know that AppDelegate is a singleton? – davbryn Nov 16 '13 at 22:58
  • Singletons are fine when used judiciously. The linked article doesn't highlight the dangers, doesn't advice caution. Score, fine. Node/object references, not so much. This post sums up what I feel about singletons and the more we can break that pattern, the better: http://stackoverflow.com/a/5913789/201863 PS: AppDelegate is not a singleton. Nothing stops you from creating multiple instances of it, it doesn't have a sharedXxx accessor either. – CodeSmile Nov 17 '13 at 00:08
0

NSUserDefaults is a good way to store simple global data, especially if you want to persist it across application launches.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217