Search code examples
swiftanimationmultidimensional-arraysprite-kitsktexture

Swift multidimensional array of textures


I am trying to load a bunch of animated textures from a texture atlas into an array but I get an error when trying to append a frame to the array.

Basically I want to have a multidimensional array of textures where each row represents an animation which is an array of frames. Something like this:

[[FirstFrameTexture, SecondFrameTexture, ThirdFrameTexture...], //first animation
 [FirstFrameTexture, SecondFrameTexture, ThirdFrameTexture...], //second animation
 [FirstFrameTexture, SecondFrameTexture, ThirdFrameTexture...]] //third animation

I initialised an array like this:

var animations = [[SKTexture]]()

but when I try to append a texture into the array like this

animations[0].append(SKTexture(imageNamed: "test"))

I get an error on this line saying:

fatal error: Cannot index empty buffer

Any ideas on how I can solve this?


Solution

  • The first array, at index 0, isn't yet created when you try to append an animation to it.

    First add an animation embedded in an array, for example:

    animations.append([SKTexture(imageNamed: "test")])
    

    Then you can add animations in the array:

    animations[0].append(SKTexture(imageNamed: "test2"))