Yuvals
Yuvals

Reputation: 3266

How to handle scene loading delay in SpriteKit

I am loading a selection scene for a player, however, when I tap the button which moves to that scene, it takes 4-5 seconds until it reveals the new scene.

In main menu I use:

SKTransition *transition = [SKTransition fadeWithDuration:0.1];

SKScene * scene = [[SelectionScene alloc] initWithSize:self.size];

[self.view presentScene:scene transition:transition];

And inside the SelectionScene I use:

- (id) initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size]) {                

        [self setupScene];
        [self setupSelection];

    }

    return self;
}

As explained, it takes 4-5 seconds between the tap on the button until it moves to the next scene. Is there a way to setup the scene later so it first shows the next scene (I will display a loading screen) and load in background?

I have tried using :

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){

    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){


    });
});

But it won't work.

Upvotes: 1

Views: 1907

Answers (2)

user1872384
user1872384

Reputation: 7127

To avoid the delay, the best practice is to load all the screen assets first by using loadSceneAssetsWithCompletionHandler function before the game begins or after level selection.

Reference: Adventure Loads Assets Asynchronously

Upvotes: 2

therealbriansc
therealbriansc

Reputation: 77

For the simplest option, I would recommend loading an activity indicator on the current SKScene (send startAnimating message to the property), load the scene in the dispatch, then within that dispatch at the very end, send the activity indicator a message to stopAnimating.

Include this property in the interface of the current SKScene object:

@property(strong, nonatomic) UIActivityIndicatorView *activityIndicator;

Then wherever you are loading the scene (i.e. touchesEnded event), use something like this:

[self.activityIndicator startAnimating];

dispatch_async(dispatch_get_main_queue(), ^{

    PVZLevelScene *levelScene =
    [[PVZLevelScene alloc] initWithSize:self.size level:theSelectedLevel];

    [self.view presentScene:levelScene
             transition:[SKTransition flipHorizontalWithDuration:0.5]];

    [self.activityIndicator stopAnimating];

});

Upvotes: 0

Related Questions