在 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 (将#修改为@)