微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Swift 中观察不同范围内的变量

如何解决在 Swift 中观察不同范围内的变量

我正在使用 spriteKit 开发游戏,并且正在构建自定义动画处理程序类。在这个项目中,我有一个全局变量 currentState,它可以在整个游戏中改变。在其核心,动画处理程序类应该查看 currentState 何时更新,并根据其新值在给定目标上触发动画。对于我想要设置动画的每个 SKNode,我都会创建一个动画处理程序的新引用,因此它可以只管理特定节点的动画和状态。我不希望它必须每帧检查 currentState 的状态并基于此进行更新,我更喜欢在动画处理程序类中设置一个观察者,该观察者在 currentState 更改时触发。

这可能最终成为解决方案,但我不希望在 currentState 上放置观察者 didSet,当触发时,循环遍历动画处理程序类的每个实例,并运行相应的动画,如到这款游戏开发结束时,很可能会有数百个动画师类。

有没有一种方法可以从动画处理程序类中向该 currentState 变量添加属性观察器,以便在更新 currentState 时,所有动画制作实例都将收到更新调用?任何帮助表示赞赏:)

我尝试过的一些事情是: 将动画师类中的变量链接到 currentState,并在该指针上放置一个观察者:

//here is a enumeration of sample game states
enum State {
case home 
case throwing
case someOtherGameState
}

var currentState: State 
...
class Animator {
    var pointerState = currentState{
        didSet { print("the global variable was set") } 
}
//but these variables do not stay linked

}

同样,我也试图让当前状态属于一个类,因此它可以是一个引用类型,我可以通过这种方式链接它,但从来没有在变量的指针上调用 didSet。

class CurrentState  {
    var currentState: State
}
currentStateClass = CurrentState()
//creates a reference type that when copied will create a pointer to this instance

class Animator {
    var pointerState = currentStateClass.currentState {
    //creates a pointer to the currentState within each instance of this class
         didSet { print("currentState was changed") }
    }
}

但是,当运行 currentStateClass.currentState = State.throwing 之类的东西时,所有实例中的 didSet 都不会运行

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。