Hi folks!
I've been battling this issue for months now, and finally dare to ask you guys in here for help.
I'm doing my own project, where I'm developing a spritekit game. Obviously I am very new to Swift and SwiftUI, and likewise I'm also doing the 100DaysOfSwiftUI.
That said, my issue is that I have a file named "Timer.swift", that contains a variable "index", that I've said it should print every time that it updates the index (that is every second).
My other file "TimeTable.swift" contains a struck with all the swiftUI information for my scene.
The frustrating bit is that I get an update in my prompt, so I know that the Timer.swift file updates my index, but for some reason it doesn't send it through my @stateobject.
For overview I'll now post the main bits of the two files:
(TimeTable.swift)
struct TimeTable: View {
@StateObject var TimeUpdater = UpdaterViewModel()
@ObservedObject var scene = GameScene()
var percent: CGFloat = 0.8
var body: some View {
VStack {
HStack(spacing: 20) {
HStack{
Image(systemName: "trophy.fill")
Text("\(TimeUpdater.index)")
}
(Timer.swift)
class UpdaterViewModel: ObservableObject {
@State var isGameActiveModel = GameScene()
@Published var index: Int = 0 {
willSet {
objectWillChange.send()
}
}
var timer: Timer?
func startTimer() {
// Invalidate the existing timer if there is one
timer?.invalidate()
// Create a new timer that repeats every second
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
// Increment the high score by 1 every second
self.index += 1
print(self.index)
}
// Ensure the timer fires immediately upon starting
timer?.fire()
}
}
I know there are some redundant code in there, but I am trying. I've learned multiple places about the "make it work, and then make it pretty" filosofi, so right now my focus is just to make it work somehow. But please ask if there is anything I haven´t explained well enough.
Would really appreciate if you guys can help somehow! 🙏
//Rasmus