4

Is it ok to configure (position sprites, add visible nodes etc) an SKScene's content in init method?

Where is the right place for such things: init? didMoveToView? something else?

AndrewShmig
  • 4,843
  • 6
  • 39
  • 68
  • Errr, yes. Do it wherever it works without issues. But what are you really getting at? Your question is rather unspecific. – CodeSmile Mar 09 '14 at 21:45
  • @LearnCocos2D, all I want to know, is there any right method to use for scene initialization/configuration. Thats all :) – AndrewShmig Mar 09 '14 at 22:03
  • 1
    Init is for initializing, except where you can't. ;) For example self.view is nil on init so any setup code that needs the view has to be run in didMoveToView – CodeSmile Mar 09 '14 at 22:04
  • @LearnCocos2D, so, if I don't use any UIKit views I can freely configure my SKScene in init method? But, if I want, for instance, to add UIButton the best place for that is didMoveToView method. Am I right? If yes - please, post your comments as an answer and I'll accept it. – AndrewShmig Mar 09 '14 at 22:18

1 Answers1

8

didMoveToView: is called every time the scene is presented by an SKView. Pros of positioning and adding sprites in didMoveToView: You can initialise many views without them grabbing a lot of memory. Cons: If you remove a view and then add it again didMoveToView: is called again. This means that you need to be sure to reset your scene in the beginning of didMoveToView: (only if you intend to remove and add again).

init is called when you initialise the SKScene. Pros of using init for positioning and adding sprites: It is only called once, and everything will be ready once you present it on the scene. If you need to preload scenes for quick switching this might be handy. Cons: Each scene will take up the memory it needs to perform all the adding of sprites when init'ed and not when its shown.

Personally, I prefer to do everything in the init method.

Theis Egeberg
  • 2,556
  • 21
  • 30