2016-04-08 112 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類的字典屬性中加載它。另外,在場景之間轉換時,該字典將在場景的瑕疵中生存下來,並且在應用程序還活着時會持續存在。