how to chang to value in Skscene ? i have a class (xiangcene) and the time1 need to change through the button. how can i do that?
struct xiang: View {
@ObservedObject var skc = xiangcene()
var xiangview:SKScene {
let scene = xiangcene()
scene.scaleMode = .fill
return scene
}
var body: some View {
ZStack{
SpriteView(scene: xiangview)
Button("timeset"){
skc.time1 = 60 // it no change the value
}
}
}
}
class xiangcene:SKScene,ObservableObject{
@Published var time1 = 1
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let wait1 = SKAction.wait(forDuration: TimeInterval(time1))
let seque = SKAction.sequence([wait1])
self.run(seque)
}
CodePudding user response:
Every time you call xiangcene(), you're creating a new instance of xiangcene. Instead, you need to create one instance that is stored on the view, passed to the SpriteView, and manipulated by the button.
Here's one solution:
struct xiang: View {
@StateObject var skc : xiangcene
init() {
let scene = xiangcene()
scene.scaleMode = .fill
_skc = StateObject(wrappedValue: scene)
}
var body: some View {
ZStack{
SpriteView(scene: skc)
Button("timeset"){
skc.time1 = 60
}
}
}
}
Here's another:
struct xiang: View {
@StateObject var skc = xiangcene()
var body: some View {
ZStack{
SpriteView(scene: skc)
Button("timeset"){
skc.time1 = 60
}
}.onAppear {
skc.scaleMode = .fill
}
}
}
Note that in both places, I'm using StateObject rather than ObservedObject, which is what I assume you want, but you can change that if that's an incorrect assumption.
I'd also consider using the Swift conventions of capitalizing type names -- it'll make it easier for people to read/parse your code.
