Swift变量不根据调用类更新

ubof19bj  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(137)

Swift newb here. ObservableObject似乎在更新时创建了一个变量的单独示例。从ContentView更新count变量比从GameScene更新count变量增加了一个单独的变量(参见控制台日志输出)。
我 * 认为 * 这是因为我正在用PlayerStats()在GameScene中创建一个新示例,但还没有找到解决方法。
什么是最简单的方法,有一个单一的来源的真理的变量-也就是说,无论是视图和SKScene可以读取和更新变量(S)?搜索没有得到我进一步比神秘的错误消息(如前所述,newb),所以提前感谢任何信息。

struct ContentView: View {
    
    @EnvironmentObject var playerstats:PlayerStats
    var scene: SKScene {
        let scene = GameScene()
        scene.size = CGSize(width: 400, height: 700)
        scene.scaleMode = .fill
        return scene
    }
    
    var body: some View {
        VStack {
            SpriteView(scene: self.scene)
                .frame(width: 400, height: 700)
                .ignoresSafeArea()
        }

        Text("Count : \(playerstats.count)")
        Button("add to count") {
            playerstats.addCount(newcount: 12)
        }.buttonStyle(.borderedProminent)
    }
}

字符串

class GameScene: SKScene, SKPhysicsContactDelegate {
    let playerstats:PlayerStats = PlayerStats()// (I've tried PlayerStats?)

    override func didMove(to view: SKView) {
        self.backgroundColor = .blue
        let count = SKLabelNode(fontNamed: "Times New Roman")
        count.text = String(playerstats.count)
        count.fontSize = 65
        count.fontColor = SKColor.green
        count.position = CGPoint(x: frame.midX, y: frame.midY)
        addChild(count)
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        playerstats.addCount(newcount: Int(40))
    }
    func didBegin(_ contact: SKPhysicsContact) {
        
    }
}


可观察对象

class PlayerStats:ObservableObject {
    @Published var count:Int = 1
    func addCount(newcount: Int) {
        print(newcount)
        print("in add")
        count += newcount
        print(count)
    }
}


控制台输出

12 // from ContentView
in add
13
40 // from GameScene
in add
41
12 // from ContentView
in add
25
40 // from GameScene
in add
81

suzh9iv8

suzh9iv81#

工作是声明一个Singleton。

class PlayerStats:ObservableObject {
    static let shared = PlayerStats()
    @Published var fuel:Int = 1
    func addFuel(newfuel: Int) {
        print("in add")
        fuel += newfuel
        print(fuel)
    }
}

字符串
并宣布

@StateObject var playerstats = PlayerStats.shared


在ContentView中。并在文本中使用.shared

Text("Fuel : \(PlayerStats.shared.fuel)")


非常感谢WorkingdogsupportUkraine的评论。

相关问题