繁体   English   中英

如何从Swift SpriteKit中的另一个SKScene访问变量

[英]How to access variables from another SKScene in Swift SpriteKit

我从其他类访问变量时遇到问题。 这是我的代码。 这是我正在尝试访问变量“ lastSelection”的类,这也是第一个调用来查看的SKScene。

class FighterPlaneselect : SKScene {
    var lastSelection:String = ""

    override func didMoveToView(view: SKView)  {
        if(true) {
            lastSelection = "Mustang"
        }
    }
}
//Here is the second class called "GameField"
class GameField : SKScene {
    var FighterPlane : FighterPlaneSelect!
    override func didMoveToView(view: SKView) {
        FighterPlane = FighterPlaneSelect()
        print(FighterPlane.lastSelection)
    }
}

无论何时打印出来,都会打印“”。 它应该打印“野马”。

在这行上:

FighterPlane = FighterPlaneSelect()

您实例化了该类的 SKScene。 问题是,它从未显示,因此从未调用过func didMoveToView(view: SKView)方法。

您需要的是对其他场景的引用。

一种可能性是执行以下操作:

class FighterPlaneSelect : SKScene {
var lastSelection:String = ""

override func didMoveToView(view: SKView)  {
        if(true) {
            lastSelection = "Mustang"
        }
    }
}

//Here is the second class called "GameField"
class GameField : SKScene {
    var fighterPlane : FighterPlaneSelect!
    override func didMoveToView(view: SKView) {
        print(FighterPlane.lastSelection)
    }
}

//Here is in the GameScene
let fighterPlaneSelect = FighterPlaneSelect
//show the scene to make it move to view
//then assign the variable inside the gameField object
let gameField = GameField()
gameField.fighterPlane = fighterPlaneSelect

您可以在场景的init方法中初始化该变量:

  class FighterPlaneselect : SKScene {
    var lastSelection:String = ""

    override  init(size: CGSize){

        super.init(size: size)

         lastSelection = "Mustang"

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func didMoveToView(view: SKView)  {

    }
}

然后像现在一样使用它:

class GameField : SKScene {
    var FighterPlane : FighterPlaneselect!

    override func didMoveToView(view: SKView) {


        FighterPlane = FighterPlaneselect(size: self.size)

        println(FighterPlane.lastSelection)
    }
}

很简单! 只需在类外声明lastSelection即可!!

class FighterPlaneselect : SKScene {
var lastSelection:String = "" //Declared in the class
}

var lastSelection:String = "" //Declared outside the class
class FighterPlaneselect : SKScene {

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM