Why is SKTextureAtlas(dictionary:) Crashing

58 Views Asked by At

I am using the following code to create a texture atlas at runtime using a single .png image sprite sheet:

func createSpriteTextureAtlas(atlasNumber atlas:Int, forWorld world:Int) {
        //load the png file
        let image = UIImage(named: "world\(world)_spritesheet\(atlas)_2048x2048.png")
        //create the dictonary
        var imageDictionary = [String: UIImage]()
        //iterate through all rows and columns and get the subimage
        var imageIndex = 0
        for row in 0...7 {
            for column in 0...7 {
                let sourceRect = CGRect(x:column * 256, y:row * 256, width:256, height:256)
                let sourceImage = image?.cgImage!.cropping(to: sourceRect)
                let subImage = UIImage(cgImage: sourceImage!)
                //add the sub image and name to the dictionary
                imageDictionary["\(imageIndex)"] = subImage
                imageIndex = imageIndex + 1
            }
        }
        //create the texture atlas using the dictionary
        spriteTextureAtlas[atlas] = SKTextureAtlas(dictionary: imageDictionary)
    }

I have a different sprite sheet for every world. I made all the sprite sheets myself using the same tool. This code works 100% of the time for most images.

For some images however, the program crashes at: SKTextureAtlas(dictionary: imageDictionary) with the error: Thread 4: EXC_BAD_ACCESS (code=1, address=0x105ff2000). The stack trace says it is crashing inside: #0 0x00000002178e2d34 in -[SKTextureAtlasPacker isFullyOpaque:] ().

The crash does not happen every time and only happens for some images. The crash never happens on the simulator. All 64 entries in the dictionary contain a valid name/UIImage pair.

Did I make a mistake inside createSpriteTextureAtlas or is this a SpriteKit bug?

P.S. I already know that I can let XCode make the texture atlas for me by using a folder with a .atlas extension but this is not what i want to do.

This code works 100% of the time for most of my sprite sheets. The crash only happens on a few sprite sheets and not every time. The images are mostly the same: same tool, same file format, same size, etc. The issue occurs with png and bmp files.

I did see this: SKTextureAtlas EXC_BAD_ACCESS and took a look at the solution but making changes to the files and trying different tools and compression levels did not help. It just seems as though SpriteKit SKTextureAtlas(dictionary:) fails with some png files.

0

There are 0 best solutions below