Sharing Data Between Scenes

When building a SpriteKit app, it can be a little daunting to share variables between scenes. Using a singleton method is a way to tackle this problem. A singleton is an object that is instantiated once. One copy of the object exists and it is accessible by other objects in different classes. This allows for data to be passed between scenes in SpriteKit.

To pass a variable called userID between two scenes (e.g., FirstScene and SecondScene), you could write the following singleton method at the top of your FirstScene.swift file. (Assuming that you're following good Swift practice and making each SKScene class have its own .swift file)

class SharedData {
    static let data = SharedData()
    var userID: Int = 0
}

Then, from the SecondScene SKScene class, you can call on the userID variable by doing the following. Within your SecondScene class (in your SecondScene.swift file), add at the top, within the class:

let sharedData = SharedData.data

Then, you can use your userID variable from the FirstScene class by calling it within methods as:

sharedData.userID

For example, to print the userID to the console within SecondScene in the didMoveToView() method, you could program:

print(sharedData.userID)