2016-04-08 113 views
3

所以我正在阅读苹果文档以获得最佳的精灵套件实践。我碰到过这个:预加载精灵套件纹理

例如,如果您的游戏在其所有游戏玩法中使用相同的纹理,您可以创建一个特殊的加载类,在启动时运行一次。您执行一次加载纹理的工作,然后将它们留在内存中。如果场景对象被删除并重新创建以重新启动游戏,纹理不需要重新加载。

而这会显着帮助我的应用程序的性能。有人能指出我正确的方向,我会如何去实现这一目标?

我认为我会调用一个函数来加载纹理的我的视图控制器?然后访问纹理图集?

回答

3

问题是,你真的想缓存那样的资源吗?不能说我曾经发现过这种性质的需求。不管怎么说,如果这样做,不知何故与您的应用程序的性能帮助,那么你可以做一个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中定义它,您将能够调用该私有init,然后TextureManager将不会是真正的单身人士。

所以,用这个代码,你可以在应用程序生命周期的最开始创建一些纹理,就像它在文档说:

例如,如果你的游戏使用了相同的纹理所有游戏, 你可能会创建一个特殊的加载类,在启动时运行一次。

并用它们填充字典。稍后,无论何时需要纹理,您都不会使用atlas.textureNamed()方法,而是从TextureManager类的字典属性中加载它。另外,在场景之间转换时,该字典将在场景的瑕疵中生存下来,并且在应用程序还活着时会持续存在。