Difference between revisions of "Safely increment variable from multiple scripts"
imported>JBurgess |
imported>Hypno88 m (corrected the example code, adding type to "myQuestScript" variable) |
||
Line 14: | Line 14: | ||
Event OnDeath(Actor akKiller) | Event OnDeath(Actor akKiller) | ||
; increment dead count | ; increment dead count | ||
myQuestScript = GetOwningQuest() as MS06Script | MS06Script myQuestScript = GetOwningQuest() as MS06Script | ||
myQuestScript.DeadCultists = myQuestScript.DeadCultists + 1 | myQuestScript.DeadCultists = myQuestScript.DeadCultists + 1 | ||
if myQuestScript.DeadCultists >= myQuestScript.TotalCultists | if myQuestScript.DeadCultists >= myQuestScript.TotalCultists | ||
Line 28: | Line 28: | ||
Event OnDeath(Actor akKiller) | Event OnDeath(Actor akKiller) | ||
; increment dead count | ; increment dead count | ||
myQuestScript = GetOwningQuest() as MS06Script | MS06Script myQuestScript = GetOwningQuest() as MS06Script | ||
myQuestScript.IncrementDeadCultists() | myQuestScript.IncrementDeadCultists() | ||
endEvent | endEvent |
Latest revision as of 23:21, 16 March 2015
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