UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Sending game timer from one file to another

Forums > SwiftUI

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

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.