我在阅读苹果的最佳Sprite Kit实践文档时看到了以下内容:
例如,如果您的游戏在所有游戏过程中使用相同的纹理,则可以创建一个特殊的加载类,在启动时运行一次。您只需一次加载纹理并将其保留在内存中即可。如果场景对象被删除并重新创建以重新开始游戏,则无需重新加载纹理。
这将显著提高我的应用程序性能。请问有人能指点我如何实现这一点吗?
我想我需要调用一个函数来在我的View Controller中加载纹理。然后访问该纹理图集?
我在阅读苹果的最佳Sprite Kit实践文档时看到了以下内容:
例如,如果您的游戏在所有游戏过程中使用相同的纹理,则可以创建一个特殊的加载类,在启动时运行一次。您只需一次加载纹理并将其保留在内存中即可。如果场景对象被删除并重新创建以重新开始游戏,则无需重新加载纹理。
这将显著提高我的应用程序性能。请问有人能指点我如何实现这一点吗?
我想我需要调用一个函数来在我的View Controller中加载纹理。然后访问该纹理图集?
问题是,你真的想那样缓存资源吗?我从来没有发现过需要那种东西。无论如何,如果这样做在某种程度上有助于应用程序的性能,那么你可以创建一个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
类的字典属性中加载它。此外,在场景之间进行转换时,该字典将在场景释放时幸存下来,并在应用程序存活时持久存在。