Help with how to use Race and concurrency

Hi there,

I have a class object that runs a “run_lifetime” function that sleeps for X seconds and then sets a flag variable “isActive” to false.

I also have a collectible object device that has a subscribed function for the OnCollected event. When a player collects the object, then the same isActive variable will get set to false.

I set up the object and collectible so they go back into an “unused” stack (isActive should be false for those objects there). The issue is when a player will collect an active collectible object, the object goes to this inactive stack and when the object then becomes active shortly again, I think its lifetime timer is still running and going to set the flag isActive to false when it’s actually still in use.

Basically I want to know how to cancel the run_lifetime async function or use a race setup to make it so that when a player collects the object and the OnCollected function happens, the run_lifetime function does not continue. Does anyone know how to set this up in this scenario?

To set up a race for the two you can try the following

race:
    run_lifetime()
    block:
        collectible.OnColleted.Await()
        # Deactivate the collectible
        # Add it to the stack

This way, the run_lifetime will be cancelled if the collectible is collected before it completes.

1 Like

Thank you so much! I actually was coming back to say I also had figured it out, which is the way you pretty much wrote it too! :blush: I am new to using Race and didn’t know how it worked with the events (haven’t used Await before), thanks I appreciate the reply

Yeah I wrote a singular function to do that race block

    doRaceItemBoxEvent(itemManager_counter : itemManagerStats)<suspends>:void =
        # race function for handling which event happens first - collecting item box by player or lifetime timer running out
        # should cancel the other event when one has occurred
        # this avoids issues with setting flags if a player collects it and the lifetime timer were to continue

        maybeCollectible := Get_itemBoxCollectible() # returns an option var of collectible_object_device

        if (currCollectible := maybeCollectible?):
            race:
                block:
                    Run_lifetimeTimer(itemManager_counter)
                block:
                    currCollectible.CollectedEvent.Await()

(there’s other code that handles all the other details of “creating” / “destroying” the collectible item box objects but those are tested and work separately from this).

I tested it in the game and my item box collectible objects no longer have the issue of their lifetime being cut short anymore :grin: thanks again~

1 Like

Nice one for figuring it out. Glad you got it working :slight_smile:

1 Like