Reputation: 491
Hello guys i have made the first Level of my game, but always when i go from the main menu screen to the first level the screen freezes for like 2 Seconds and the transition from the Main screen to the game is very delayed and laggy and it sometimes doesn't even show up. Is there a way to preload the Scene in the background to prevent the lag?
Upvotes: 1
Views: 1425
Reputation: 789
Swift 5 version of @hamobi answer
file: DispatchQueueExtensions.swift
import Foundation
extension DispatchQueue {
static func background(_ task: @escaping () -> Void) {
DispatchQueue.global(qos: .background).async {
task()
}
}
static func main(_ task: @escaping () -> Void) {
DispatchQueue.main.async {
task()
}
}
}
file: GameScene.swift
extension GameScene {
class func create(completion: @escaping (_ scene: GameScene) -> Void) {
DispatchQueue.background {
let scene = GameScene()
DispatchQueue.main {
completion(scene)
}
}
}
}
Usage:
GameScene.create(completion: { [weak self] scene in
let transition = SKTransition.doorway(withDuration: 1.0)
self?.view?.presentScene(scene, transition: transition)
})
Upvotes: 0
Reputation: 8130
you can load the resources for the scene in a different thread. I do this in my game to get really snappy scene transitions despite the fact im loading tons of resources.
make a static function in your scene class to preload your scene
class func createResources(withCompletion: (scene: BaseScene) -> ()){
// load resources on other thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
let scene = YourScene()
// callback on main thread
dispatch_async(dispatch_get_main_queue(), {
// Call the completion handler back on the main queue.
withCompletion(scene: scene)
});
})
}
call it like this
YourScene.createResources(withCompletion: {
[weak self]
scene in
self!.skView.presentScene(scene)
})
So the way to use this is to build your scene in advance on the different thread. since its running on a different thread you shouldnt get that awkward pause.
for example. lets say the player reaches the goal of beating the level. before I was using this method the game would pause for a second before loading the next scene.
When the player beats the level now I still allow them to move around until the next scene has loaded and then the player will instantly shoot into the next level creating an instant transition.
you can see it here when the ship is hyperspacing between levels. there are a lot of resources loading but the transitions are seamless. https://www.youtube.com/watch?v=u_bXA3woOmo
Upvotes: 1