My question on StackOverflow - https://stackoverflow.com/questions/66927068/swiftui-spriteview-issue-stopped-adding-nodes
If to comment score += 1 - everything start working again!
My code on GitHub: github.com/alexpilugin/ap-swiftui-spriteview-ios14 - https://github.com/alexpilugin/ap-swiftui-spriteview-ios14
import SwiftUI
import SpriteKit
class GameSettings: ObservableObject {
@Published var score: Int = 0
}
class GameScene: SKScene {
@Binding var score: Int
init(score: BindingInt) {
_score = score
super.init(size: CGSize(width: 300, height: 400))
self.scaleMode = .fill
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func didMove(to view: SKView) {
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
}
override func touchesBegan(_ touches: SetUITouch, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let box = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
self.addChild(box)
// score += 1 //----- The issue is here
print("Nodes: \(self.children.count), score: \(score)")
}
}
struct ContentView: View {
@EnvironmentObject var settings: GameSettings
var scene: SKScene {
let scene = GameScene(score: $settings.score)
//scene.showsFPS = true //---- ERROR
//scene.showsNodeCount = true //---- ERROR
return scene
}
var body: some View {
VStack {
SpriteView(scene: scene)
.frame(width: 300, height: 400)
Text("Score: \(self.settings.score)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(GameSettings())
}
}