Issue with spawning guards

Hey everyone, I’m trying to spawn a limited amount of guards but something doesn’t work.

As you can see in SpawnEnemies() below I take a guard_spawner_device, spawn 1 guard and add 1 to AliveEnemies.

The problem is that the way I do it now the Spawn() can fail (I guess because the Target is invalid although I don’t understand how it can become invalid) but set AliveEnemies succeeds.

How can I make sure that either both or none of EnemySpawner.Spawn(Target) and set AliveEnemies += 1 succeeds?

room_controller := class(creative_device):

    @editable
    MaxFloorSize:int = 15
    @editable
    MaxEnemiesAlive:int = 3
    @editable
    EnemySpawners:[]guard_spawner_device = array{guard_spawner_device{}}
    @editable
    EliminatedTrigger:trigger_device = trigger_device{}

    var AliveEnemies:int = 0
    var KilledEnemies:int = 0

    OnBegin<override>()<suspends>:void=     
        EliminatedTrigger.TriggeredEvent.Subscribe(OnEnemyEliminated)
        UpdateLoop()

    OnEnemyEliminated(Elimintated:?agent):void=       
        set KilledEnemies += 1 
        set AliveEnemies -= 1 

    UpdateLoop()<suspends>:void=         
        loop:            
            Sleep(2.0)
                if ((KilledEnemies + AliveEnemies) < MaxFloorSize):
                    SpawnEnemies()
                             
    SpawnEnemies():void=
        Players := GetPlayspace().GetPlayers()           
            if (AliveEnemies < MaxEnemiesAlive): 
                x:int = GetRandomInt(0, EnemySpawners.Length - 1)
                i:int = GetRandomInt(0, Players.Length - 1)
                if (EnemySpawner:guard_spawner_device := EnemySpawners[x]):              
                    if (Target:agent := Players[i]):
                            EnemySpawner.Spawn(Target)
                            set AliveEnemies += 1

Hey @lwillsl !

One way to make sure that either both or none of EnemySpawner.Spawn(Target) and set AliveEnemies += 1 succeeds would be to listen to the Guards Spawner device’s
SpawnedEvent:

@doc("Signaled when a guard is spawned.{
     }Sends the `agent` guard who was spawned.")
SpawnedEvent<public>:listenable(agent) := device_event_agent{ EventName := "On Spawned" }

Your new method listening to this event would be responsible to increment AliveEnemies. Thus, if somehow the Guard did not spawned, you will not receive the SpawnedEvent and as such you will not increment the AliveEnemies count.

On another note, Spawn(Target) is meant to Spawn a guard and make so Target automatically hires him. Make sure that is what you want as I don’t have the full gameplay context :slight_smile:

Additionally, by doing this, you could also remove the UpdateLoop method and make this script entirely event based (OnEnemyEliminated and OnSpawnedEnemy would re-evaluate the need to spawn new enemies).

Hope that helps,

Guillaume

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.