Safely increment variable from multiple scripts

From the CreationKit Wiki
Jump to navigation Jump to search

The Problem[edit | edit source]

Say the player needs to kill X of some creature. One common way to do this is put an OnDeath script on all the creatures, increment a quest variable, then do something when the count gets to the right number.

This can cause problems because it isn’t thread safe – meaning if two enemies die at exactly the same moment, one may end up bashing the other, preventing the player from getting credit for one of the kills.

The Solution[edit | edit source]

Instead of incrementing the variable from the other scripts, it's better to use a function on the quest script (where applicable) which increments the variable and does whatever it needs to when the count gets to the right number. This is thread-safe (because it is a function call). So, for example, instead of doing this:

 ; WRONG WAY
 Event OnDeath(Actor akKiller)
       ; increment dead count
       MS06Script myQuestScript = GetOwningQuest() as MS06Script
       myQuestScript.DeadCultists = myQuestScript.DeadCultists + 1
       if myQuestScript.DeadCultists >= myQuestScript.TotalCultists
             GetOwningQuest().SetStage(100)
       endif
 endEvent

I changed it to this on the actor script:

 ; RIGHT WAY
 Event OnDeath(Actor akKiller)
       ; increment dead count
       MS06Script myQuestScript = GetOwningQuest() as MS06Script
       myQuestScript.IncrementDeadCultists()
 endEvent

And then put this on MS06Script:

 function IncrementDeadCultists()
       DeadCultists = DeadCultists + 1
       if DeadCultists >= TotalCultists
             setStage(100)
       endif
 endFunction