2

Since I am new to swift and spriteKit, I have read the document from apple:

preload document from Apple

I tried to load some images like this code below:

let textureArray = [SKTexture(imageNamed: "enemy1"),SKTexture(imageNamed: "enemy2"),SKTexture(imageNamed: "enemy3")]

override func viewDidLoad() {
    super.viewDidLoad()
    SKTexture.preload(textureArray) {
        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            if let scene = SKScene(fileNamed: "GameScene") {
                // Set the scale mode to scale to fit the window
                scene.scaleMode = .aspectFill
                
                // Present the scene
                view.presentScene(scene)
            }
            
            view.ignoresSiblingOrder = true
            
            view.showsFPS = true
            view.showsNodeCount = true
        }
    }
}

Now, my question is how to use the textures I have loaded? For example, in another swift file, I have a class called player, how could I use the textures I have loaded to crate a SkspriteNode? How to pass the textureArray to that class?

Fake Panda
  • 35
  • 2
  • You have pretty much everything explained [here](https://stackoverflow.com/questions/37119707/how-does-sktexture-caching-and-reuse-work-in-spritekit). What is not explained, is how SpriteKit clears memory from image data after all strong references, which is mentioned [here](https://stackoverflow.com/a/20892648/3402095). From my experience, it seems like even you don't hold strong reference on atlases/textures, they seem to be cached (I haven't had lag after preloading them). But I guess its more safe to build some kind of your own cache class. Something simple, like dictionary with textures. – Whirlwind Feb 23 '22 at 02:09
  • And when it comes to passing data between objects.. That kinda doesn't have anything with `SpriteKit`. You can pass it in any way you would do in any other iOS application. The point is, you keep track of strong references (say in Your `TextureManager` class) and remove them when textures are no longer needed (eg. you change the level or so...) – Whirlwind Feb 23 '22 at 02:15
  • *I my first comment I wanted to say "after all strong references are removed from the texture object" :) I somehow ate half of a sentence lol – Whirlwind Feb 23 '22 at 02:18

0 Answers0