I am trying to figure out what is the difference between these two examples and how preloadTextureAtlases :withCompletionHandler works. Here is the code:
//GameScene.m
-(void)didMoveToView:(SKView *)view {
//First I create an animation, just a node moving from one place to another and backward.
//Then I try to preload two big atlases
[SKTextureAtlas preloadTextureAtlases:@[self.atlasA, self.atlasB] withCompletionHandler:^{
[self setupScene:self.view];
}];
I suppose that preloadTextureAtlases doing loading on background thread because my animation is smooth?
But are there any differences(or it can be problematic somehow) to call preloadTextureAtlases from background thread? Like this:
//GameScene.m
- (void)loadSceneAssetsWithCompletionHandler:(CompletitionHandler)handler {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[SKTextureAtlas preloadTextureAtlases:@[self.atlasA, self.atlasB] withCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self setupScene:self.view];
});
}];
if (!handler){return;}
dispatch_async(dispatch_get_main_queue(), ^{
handler();
});
});
}
And then call this method from didMoveToView:
[self loadSceneAssetsWithCompletionHandler:^{
NSLog(@"Scene loaded");
// Remove loading animation and stuff
}];
You can preload in the background but the question is why would you? Chances are your game cannot start playing until all required assets are loaded so the user will have to wait regardless.
You can preload whatever assets you need to get the game started and background load any additional assets you might require during later game play. Those kind of circumstances are really only required in very complex games and not on the iOS platform.
As for your question on loading in the background while game play is ongoing, there is no definite answer. It all depends on how big of a load, your CPU load, etc... Try it out and see what happens because it sounds like you are asking questions on issues you have not tried out first.
If you are really intent on background tasks, remember that you can add a completion block to your custom methods like this:
-(void)didMoveToView:(SKView *)view {
NSLog(@"start");
[self yourMethodWithCompletionHandler:^{
NSLog(@"task done");
}];
NSLog(@"end");
}
-(void)yourMethodWithCompletionHandler:(void (^)(void))done; {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// a task running another thread
for (int i=0; i<100; i++) {
NSLog(@"working");
}
dispatch_async(dispatch_get_main_queue(), ^{
if (done) {
done();
}
});
});
}