预加载Sprite Kit纹理

3

我在阅读苹果的最佳Sprite Kit实践文档时看到了以下内容:

例如,如果您的游戏在所有游戏过程中使用相同的纹理,则可以创建一个特殊的加载类,在启动时运行一次。您只需一次加载纹理并将其保留在内存中即可。如果场景对象被删除并重新创建以重新开始游戏,则无需重新加载纹理。

这将显著提高我的应用程序性能。请问有人能指点我如何实现这一点吗?

我想我需要调用一个函数来在我的View Controller中加载纹理。然后访问该纹理图集?

1个回答

4

问题是,你真的想那样缓存资源吗?我从来没有发现过需要那种东西。无论如何,如果这样做在某种程度上有助于应用程序的性能,那么你可以创建一个TextureManager类,它将是单例的(为TextureManager类创建单独的文件),像这样:

class TextureManager{

    private var textures = [String:SKTexture]()

    static let sharedInstance = TextureManager()

    private init(){}


    func getTexture(withName name:String)->SKTexture?{ return textures[name] }

    func addTexture(withName name:String, texture :SKTexture){


        if textures[name] == nil {
            textures[name] = texture
        }
    }

    func addTextures(texturesDictionary:[String:SKTexture]) {

        for (name, texture) in texturesDictionary {

            addTexture(withName: name, texture: texture)
        }
    }

    func removeTexture(withName name:String)->Bool {

        if textures[name] != nil {
            textures[name] = nil
            return true
        }
        return false
    }
}

在这里,你使用字典并将每个纹理与其名称关联起来。这是一个非常简单的概念。如果字典中没有相同名称的纹理,则添加它。但要注意不要过早优化。

用法:

 //I used didMoveToView in this example, but more appropriate would be to use something before this method is called, like viewDidLoad, or doing this inside off app delegate.
    override func didMoveToView(view: SKView) {

        let atlas = SKTextureAtlas(named: "game")

        let texture = atlas.textureNamed("someTexture1")

        let dictionary = [
             "someTexture2": atlas.textureNamed("someTexture2"),
             "someTexture3": atlas.textureNamed("someTexture3"),
             "someTexture4": atlas.textureNamed("someTexture4"),

        ]

        TextureManager.sharedInstance.addTexture(withName: "someTexture", texture: texture)
        TextureManager.sharedInstance.addTextures(dictionary)

    }

如我所说,你需要将TextureManager的实现放在一个单独的文件中,以使其成为真正的单例。否则,如果你将其定义在例如GameScene中,你将能够调用该私有初始化方法,那么TextureManager就不是一个真正的单例。
因此,使用这段代码,你可以在应用程序生命周期的最开始创建一些纹理,正如文档中所说:
“例如,如果你的游戏对所有游戏过程都使用相同的纹理,你可以创建一个特殊的加载类,在启动时运行一次。”
然后,将它们添加到字典中。之后,每当你需要一个纹理时,你将不再使用atlas.textureNamed()方法,而是从TextureManager类的字典属性中加载它。此外,在场景之间进行转换时,该字典将在场景释放时幸存下来,并在应用程序存活时持久存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接