在104次调用后,从SKView获取SpriteKit纹理返回nil

时间:2018-04-30 16:33:55

标签: sprite-kit scenekit

创建纹理时,我在SpriteKit中有一些奇怪的行为。下面的功能显示了我在做什么。简而言之,我在SceneKit中使用一组颜色(想象像素/体素)制作SCNNode。它就像一个魅力。但是,经过104次调用后返回的纹理为零。然后,它会被击中或遗漏纹理是否为零。我还提供准确的颜色信息。思考?

   func create2dModelSK(with colors: [String]) -> SCNNode? {
    let geo = SCNBox(width: 1.0, height: 1.0, length: 0.1, chamferRadius: 0.0)

    let base = SCNNode(geometry: geo)

    let view = SKSpriteNode(color: .white, size: CGSize(width: 160, height: 160))
    view.anchorPoint = CGPoint(x: 0, y: 1)
    var xOffset = 0
    var yOffset = 0
    var count = 0
    for _ in 0...15 {
        for _ in 0...15 {
            guard let newColor = UIColor(hexString: "#" + colors[count] + "ff") else { return base }

            let n = SKSpriteNode(color: newColor, size: CGSize(width: 10, height: 10))
            n.anchorPoint = CGPoint(x: 0, y: 1)
            n.position = CGPoint(x: xOffset, y: yOffset)
            view.addChild(n)
            xOffset += 10
            count += 1
        }
        xOffset = 0
        yOffset -= 10
    }
    let skView = SKView(frame: CGRect(x: 0, y: 0, width: 160, height: 160))

    let texture = skView.texture(from: view)
    //AFTER being called 104 times, texture is nil.
    let faceMaterial = SCNMaterial()
    faceMaterial.diffuse.contents = texture

    let sideMaterial = SCNMaterial()
    sideMaterial.diffuse.contents = UIColor.white

    let materialsForBox = [faceMaterial,sideMaterial,faceMaterial,sideMaterial,sideMaterial,sideMaterial]
    base.geometry?.materials = materialsForBox

    let scale = SCNVector3(x: 0.1, y: 0.1, z: 0.1)
    base.scale = scale

    return base
}

1 个答案:

答案 0 :(得分:1)

这是autoreleasepool派上用场的地方,它允许您在autoreleasepool完成后释放内存,这样在再次使用之前不会耗尽空间。

当然这不会解决您的主要问题,即创建太多纹理和耗尽内存空间,但它会让您至少再做一些因为它会释放{{{ 1}}坚持。

view.texture(from:node)