7thSage again. Before getting into this lesson, I’d like to spend some time doing a bit of refactoring. The main goals here are to make things a bit cleaner, and to remove a number of string lookups to make our code safer to use. To keep things as simple as possible, I’ll be splitting the repository for this one into two sections, the first commit will be for the refactor, and I’ll add a second one for all the Victory condition pieces.
Before starting to refactor, there are two things I’d suggest. Make sure the code works before you start. If you’re code isn’t working beforehand, it will be much harder to figure out if your problems are new or old. And second, back up your code, preferably using version control, but make sure you have that backup.
As a quick tip, a lot of what we are replacing are lines with some sort of string lookup, so once you get to the script that needs a line edited, it will often be quickest to find the line by just keeping your eye out for the highlighted strings in the editor. Also instead of trying to navigate the entire tree to find files, I’d suggest using the search, “Filter Files” section at the top of the FileSystem tab.

Also I’d like to apologize in advance for the long post.
Globals
There are a few things that we access throughout our project that I think it would make easier if we had better access to.
Create a new folder in the “Scripts” folder named “Global” and inside it create a new script named “Global.gd”
In “Project->Project Settings” under the Autoload tab. Click the folder icon next to the box marked Path and navigate to the script we just created. It will auto add the Node Name “Global”, this is what we’ll access the script with in our code. When we run the scene, you’ll see a node created named “Global” in the scenetree. Once you have picked the script, click on the button “Add”.

The script itself is pretty simple. First, we store a variable to hold our Battle Controller. This way we’ll be able to access it without having to deal with the scene tree and any potential changes to the hierarchy breaking our access to it.
Next is a function I had on the Battle Controller, GetParentUnit(), we’ll delete that and move it here. We’ll have to fix any paths that were pointing to the old location. Which We’ll work on shortly as we replace other bits, or you can go ahead and fix any broken links.
The next two functions help us get the children of a node. Previously we’ve been having to type multiple lines in every script we wanted to access a child. This will simplify those calls down to a single line that is clean and easy to use. It also adds the ability to specify the type as an actual type, instead of passing along a string for the type which can be prone to errors that are hard to spot.
extends Node var battleController:BattleController static func GetParentUnit(node:Node): var parent = node.get_parent() if parent == null: return null if parent is Unit: return parent return GetParentUnit(parent) static func GetChildrenOfType(obj:Node, type:GDScript): var children:Array[Node] = obj.get_children() var filtered:= Array([], TYPE_OBJECT, &"Node", type) filtered.assign(children.filter(func(node): return is_instance_of(node, type) && !node.is_queued_for_deletion())) return filtered static func GetChildOfType(obj:Node, type:GDScript): var children = GetChildrenOfType(obj, type) return children[0] if children else null
Now to set the battleController variable, lets go to the script “BattleController.gd” and we’ll set it in the _init() function. This way we never have to navigate the tree to set or retrieve the variable.
If you haven’t deleted the GetParentUnit() function already, go ahead and do that while we have it open.
func _init(): Global.battleController = self
Ability
Before we get into the swapping out code to use the functions in our Global script, lets work on setting up a couple more things for the changes ahead. First up, in “Ability.gd” we’ll add a variable to store the unit that the ability is on, which will make it easier to refer back up to the unit, even without using our global helper function. While we are here, we’ll also take a quick moment to use our new global variable to get the battle controller without relying on finding it from root.
var unit:Unit func _ready(): battle = Global.battleController
Unit
We need a few extra variables in one more place, “Unit.gd”. The variables here will be the biggest help in eliminating a bunch of string calls in our code. Just add all these to the top with the other variables.
var stats: Stats var status: Status var movement: Movement var equipment: Equipment var job: Job var health: Health var mana: Mana var alliance: Alliance var rank: Rank var attack: Ability var catalog: AbilityCatalog
Unit Factory
Now for us to have easy access to these variables, we need a way to set them, and if we need to use strings to set them in the first place, we wouldn’t be eliminating much. So the best place to add all these objects is when we create them in the first place. So lets move on to UnitFactory.gd
With the exception of AbilityCatalog, we’ll just be setting the variables at the end of each function that we use to create them.
In AddStats() we’ll add at the end
obj.stats = s
In AddStatus() we’ll add at the end
obj.status = status
In AddEquipment() we’ll add at the end
obj.equipment = equipment
In AddHealth() we’ll add at the end
obj.health = health
In AddMana() we’ll add at the end
obj.mana = mana
In AddJob() we’ll add at the end
obj.job = job
In AddAlliance() we’ll add at the end
obj.alliance = alliance
In AddRank() we’ll add at the end
obj.rank = rank
In AddLocomotion() we’ll add at the end
obj.movement = move
In AddAttack() we’ll add at the end
attack.unit = obj obj.attack = attack
And in AddAbilityCatalog() we need to make a couple additions, the first is just after we add the catalog as a child to abilities
obj.catalog = abilityCatalog
Next, at the end of the inner for loop creating our spells, we’ll take the time to set the “unit” variable on the Abilities.
ability.unit = obj
While we are here, we have a way to access the Battle Controller more easily, so we don’t need to pass along the battle controller through all the functions. So in Create(), we can remove the argument for passing in BattleConroller, shortening it to
static func Create(name:String, level:int):
And we’ll be removing it from CreateRecipe() as well so the return line can be shortened as well.
return CreateRecipe(recipe, level)
Next, in CreateRecipe() we can remove it from the arguments
static func CreateRecipe(recipe:UnitRecipe, level:int):
The line that needs a reference to the Battle Controller was using it so we could parent our units to it. I want to make one change before getting to that though. I’d like to keep our units a bit more organized, so we’ll create a new node “Units” and put all our units as children of this to keep them in one place.
So lets go to our Battle.tscn, and under the Battle Controller node, create a new child node of type Node3D named “Units”.
Now we can update that line that we broke, “_owner.add_child(obj)”, removing the Battle Controller reference, but instead of calling directly from the Battle Controller, we’re going through the new “Units” node. I know I just talked about getting rid of string lookups, but I didn’t want to create an extra variable for this, so its probably fine. We have a few in the Factory at any point.
Global.battleController.get_node("Units").add_child(obj)
One last place we need to deal with to finish the change. In “InitBattleState.gd”, in the function SpawnTestUnits() we need to update the call to the factory
var unit:Unit = UnitFactory.Create(recipe, level)
Global.battleController
Now that we have all our variables figured out, lets start using them, starting primarily with the Battle Controller variable in Global. I’m just listing the lines and scripts I changed here. If it isn’t clear where the line is, feel free to check out the repository to compare.
In BattleState.gd in the _ready() function
_owner = Global.battleController
In TurnOrderController in the Round() function we’ll set the bc variable with our global, and while we’re here, there are also a couple places we call ‘.get_node(“Stats”)’ that we’ll replace without the variables we added to our unit.
var bc:BattleController = Global.battleController
The first two are also in the Round() function, one in each of the for loops. They’ll both change to look like
var s:Stats = unit.stats
The last one is in the function GetCounter()
var s:Stats = target.stats
In BaseAbilityEffect.gd in the _ready() function
battle = Global.battleController
In HitRate.gd in the function _ready(). We have a couple changes here. First we’ll set the battle controller. Second we already previously had a variable for the hit success indicator in our Battle Controller, so we’ll make use of that to get rid of a string call, and finally we’ll swap over the GetParentUnit function to Global since we’re deleting the version on the Battle Controller.
var battle:BattleController = Global.battleController hitIndicator = battle.hitSuccessIndicator attacker = Global.GetParentUnit(self)
In BaseAbilityPower.gd in the _ready() function
battle = Global.battleController
In Mana.gd we make a couple changes. We move the unit variable up, and use the new stats variable on the unit to set our stats variable. Then to get the turnController, we use our new Global.battleController variable.
func _ready(): unit = get_parent() stats = unit.stats stats.WillChangeNotification(StatTypes.Stat.MP).connect(OnHPWillChange) stats.DidChangeNotification(StatTypes.Stat.MMP).connect(OnMHPDidChange) turnController = Global.battleController.turnOrderController turnController.TurnBeganNotification(unit).connect(OnTurnBegan)
In DurationStatusCondition.gd in the _ready() function
turnController = Global.battleController.turnOrderController
In StopStatusEffect.gd in the _enter_tree() function
hitIndicator = Global.battleController.hitSuccessIndicator
In PoisonStatusEffect.gd in the _enter_tree() function
turnController = Global.battleController.turnOrderController unit = Global.GetParentUnit(self)
In BlindStatusEffect.gd in the _enter_tree() function
hitIndicator = Global.battleController.hitSuccessIndicator
Global.GetParentUnit
Because we deleted the implementation in the Battle Controller, any script that used that will need to be replaced. We also are making use of the new variables in the Unit script to point to the nodes attached to it.
In LineAbilityArea.gd in the function GetTilesInArea()
unitTile = Global.GetParentUnit(self).tile
In KnockbackAbilityEffect.gd in the function Predict()
var attacker:Unit = Global.GetParentUnit(self)
In HealAbilityEffect.gd in the function Predict()
var attacker:Unit = Global.GetParentUnit(self)
In DamageAbilityEffec.gd in the function Predict()
var attacker:Unit = Global.GetParentUnit(self)
In AbsorbDamageAbilityEffect in the function OnApply()
var s:Stats = Global.GetParentUnit(self).stats
In WeaponAbilityPower.gd there are three spots, in the function GetBaseAttack()
var stats:Stats = Global.GetParentUnit(self).stats
In the function PowerFromEquippedWeapon()
var eq:Equipment = Global.GetParentUnit(self).equipment
In the function UnarmedPower()
var job:Job = Global.GetParentUnit(self).job
In PhysicalAbilityPower.gd in the function GetBaseAttack()
var stats:Stats = Global.GetParentUnit(self).stats
In MagicalAbilityPower.gd in the function GetBaseAttack()
var stats:Stats = Global.GetParentUnit(self).stats
In AddStatusFeature.gd in the function OnApply()
var status:Status = Global.GetParentUnit(self).status
In Equippable.gd in the function OnEquip()
node.Activate(Global.GetParentUnit(self))
In StopStatusEffect.gd there are two locations this time, in the function _enter_tree(). We’ll also be replacing the string lookup here.
myStats = Global.GetParentUnit(self).stats
And in the function OnAutomaticHitCheck()
var _owner:Unit = Global.GetParentUnit(self)
In HasteStatusEffect.gd in the function _enter_tree()
myStats = Global.GetParentUnit(self).stats
In BlindStatusEffect.gd in the function OnHitRateStatusCheck()
var _owner:Unit = Global.GetParentUnit(self)
In SlowStatusEffect.gd in the function _enter_tree()
myStats = Global.GetParentUnit(self).stats
Unit Variables
Here we’ll make use of the variables we added to Unit. The changes here are all small, but we’ll be eliminating a lot of string calls.
In ActionSelectionState.gd in the LoadMenu() function
catalog = turn.actor.catalog
In CategorySelectionState.gd in the LoadMenu() function
var catalog:AbilityCatalog = turn.actor.catalog
In MoveSequenceState.gd in the Sequence() function
var m:Movement = turn.actor.movement
In MoveTargetState.gd in the Enter() function
var mover:Movement = turn.actor.movement
In ExperienceManager.gd in the AwardExperience() function, though this one is currently only used in a test function
var r:Rank = unit.rank
In DefaultAbilityEffectTarget.gd in the IsTarget() function
var s:Stats = tile.content.stats
In KOdAbilityEffectTarget.gd in the IsTarget() function
var s:Stats = tile.content.stats
In UndeadAbilityEffectTarget.gd in the IsTarget() function
var s:Stats = tile.content.stats
In EarthquakeAbilityEffect.gd in the OnApply() function
var s:Stats = defender.stats
In HealAbilityEffect.gd in the OnApply() function
var s:Stats = defender.stats
In InflictAbilityEffect.gd in the OnApply() function
var status:Status = unit.status
In KnockbackAbilityEffect.gd in the OnApply() function we have two small changes
var s:Stats = defender.stats
and a little further down
var bumpStats:Stats = knockbackLocation.content.stats
In ReviveAbilityEffect.gd in the Predict() and OnApply() functions
var s:Stats = target.content.stats
In ATypeHitRate.gd in the GetEvade() function
var s:Stats = target.stats
In STypeHitRate.gd in the GetEvade() function
var s:Stats = target.stats
In MagicalAbilityPower.gd in the function GetBaseDefense()
var stats:Stats = target.stats
In PhysicalAbilityPower.gd in the function GetBaseDefense()
var stats:Stats = target.stats
In AbilityRange.gd we can simplify the var unit:Unit to
var unit:Unit: get: return get_parent().unit
In AbilityMagicCost.gd in the OnCanPerformCheck() and OnDidPerformNotification() functions
var s:Stats = ability.unit.stats
In Health.gd in the _ready() function
stats = get_parent().stats
In Job.gd in the Employ() function we can replace the for loop with the line
stats = get_parent().stats
In Rank.gd in the _ready() function
stats = get_parent().stats
In StatModifierFeature.gd in the var stats “get:”
return _target.stats
In PoisonStatusEffect.gd in the OnNewTurn() funtion
var s:Stats = unit.stats
In StatPanel.gd in the Display() function
var stats:Stats = obj.stats
GetChildOfType and GetChildrenOfType
In the past to get all the children of any given node that match a type, it took us several lines, with a syntax that was hard to remember. Now we can replace those multiple lines with a single line in most cases. That does however mean that the changes here will be more than just replacing a piece of a single line, but multiple lines all at once.
Before moving on, our code should work at this point, so feel free to give it a test.
In ParseJobs.gd in the GetFeature() function, I rename the variable in the for loop to “featureArray” and replace the first two lines with this
var featureArray:Array[Feature] = Global.GetChildrenOfType(job, Feature)
In AbilityTargetState.gd in the function Enter(), the two lines after super() get condensed into one line
ar = Global.GetChildOfType(turn.ability, AbilityRange)
In ActionSelectionState.gd in the LoadMenu() function. This one isn’t any shorter, but it does get rid of a string
var cost:AbilityMagicCost = Global.GetChildOfType(ability, AbilityMagicCost)
In ConfirmAbilityTargetState.gd we have a couple places to edit. In the function Enter(), the two lines after super() get condensed into one line
aa = Global.GetChildOfType(turn.ability, AbilityArea)
We have two lines in IsTarget() that need edited
var children:Array[BaseAbilityEffect] = Global.GetChildrenOfType(turn.ability, BaseAbilityEffect)
var targeter:AbilityEffectTarget = Global.GetChildOfType(child, AbilityEffectTarget)
In UpdateHitSuccessIndicator() we have three lines that need modified
var children:Array[BaseAbilityEffect] = Global.GetChildrenOfType(turn.ability, BaseAbilityEffect)
var targeter:AbilityEffectTarget = Global.GetChildOfType(child, AbilityEffectTarget)
var hitRate:HitRate = Global.GetChildOfType(child, HitRate)
In AbilityArea.gd for the function _GetRange(), we’ll simplify it down to
func _GetRange(): var range:AbilityRange = Global.GetChildOfType(self.get_parent(), AbilityRange) return range
In WeaponAbilityPower.gd in the function PowerFromEquippedWeapon(), the three lines for the features:Array get condensed down to
var features:Array[StatModifierFeature] = Global.GetChildrenOfType(item, StatModifierFeature)
In Job.gd we simplify the arrays in both Employ() and UnEmploy()
func Employ(): stats = self.get_parent().stats stats.DidChangeNotification(StatTypes.Stat.LVL).connect(OnLvlChangeNotification) var features:Array[Feature] = Global.GetChildrenOfType(self, Feature) for node in features: node.Activate(self.get_parent()) func UnEmploy(): var features:Array[Feature] = Global.GetChildrenOfType(self, Feature) for node in features: node.Deactivate() stats.DidChangeNotification(StatTypes.Stat.LVL).disconnect(OnLvlChangeNotification) stats = null
In Consumable.gd we simplify the Consume() function to
func Consume(targetObj:Node): var features:Array[Feature] = Global.GetChildrenOfType(self.get_parent(), Feature) for node in features: node.Apply(targetObj)
In Equippable.gd OnEquip() and OnUnEquip() both get simplified
func OnEquip(): if _isEquipped: return _isEquipped = true var features:Array[Feature] = Global.GetChildrenOfType(self.get_parent(), Feature) for node in features: node.Activate(Global.GetParentUnit(self)) func OnUnEquip(): if not _isEquipped: return _isEquipped = false var features:Array[Feature] = Global.GetChildrenOfType(self.get_parent(), Feature) for node in features: node.Deactivate()
In Status.gd in the function Add(), we still need two lines here. Because the array we are storing the status effect into is the base class “StatusEffect”, while the array we are getting will be the type we are looking for, we need to use “assign()” instead of just “=”. Delete the line with “var children” and the line with “filtered.assign” gets replaced with the following
filtered.assign(Global.GetChildrenOfType(self, status_effect))
And in the function Remove() we can also replace the three lines with
var condition:Array[StatusCondition] = Global.GetChildrenOfType(effect, StatusCondition)
In BaseAbilityEffect.gd in the Apply() function the two if statements we’ll swap out to use GetChildOfType(), getting rid of the last major string value we have hard coded.
if Global.GetChildOfType(self, AbilityEffectTarget).IsTarget(target) == false:
if Global.GetChildOfType(self, HitRate).RollForHit(target):
Test
Before we try renaming any nodes, this is a really good time to test our code to make sure it all works. Visually it should look the same as our previous lesson since we haven’t changed anything.
Ability Catalog Rename
When creating the abilities for the ability catalog, my workflow was mostly trying to copy chunks of one attack that was similar to what I needed. The problem that I ran into was that it was somewhat difficult trying to see which nodes were the actual type I needed. Such as ATypeHitRate vs STypeHitRate. Because they were all named the same “Hit Rate”.
With the changes we made, we can actually fix that now. Although now we need to be careful of the opposite problem, which is that it is possible to have the node name mismatched from its type.
I’ve went ahead and renamed all the “Ability Range”, “Ability Area”, “Ability Effect Target” and “Hit Rate” nodes. You don’t need to make these changes, but I think they will make it easier to piece together new skills in the future if we have the parts more clearly labeled.

Before moving on, test all the abilities to make sure everything still works. This time the aim is to make sure we didn’t break anything that wasn’t visible before renaming the nodes, or if we haven’t missed anything in the refactor. It should all be good to go and still look exactly like it did in the previous lesson. The difference now is that we are a little more free to rename nodes.
Victory Conditions
Now that we have the refactor finished, we can get to working on the actual victory conditions.
Knock-Out Status Effect
We’ll start off by including a status effect for “Knock Out”. This will let us identify characters that have been defeated, and apply things like animations when units have been defeated.
There will be three primary effects of this script
- We’ll give a visual effect to our character. For the case of the tutorial, we’ll squash them flat.
- We’ll disable them from updating their turn counters. We don’t want them taking multiple turns in a row once they have been revived.
- We’ll prevent them from taking turns in the first place.
We’ll squash and unsquash them in the _enter_tree() and _exit_tree() functions respectively. We’ll also set up listeners to handle preventing the character from continuing to take turns.
In the folder “Scripts->View Model Component->Status->Effects”, create a new script named “KnockOutStatusEffect.gd”
extends StatusEffect class_name KnockOutStatusEffect var unit: Unit: get: return Global.GetParentUnit(self) var stats:Stats: get: return Global.GetParentUnit(self).stats var turnController:TurnOrderController func _enter_tree(): unit.scale = Vector3(0.75, 0.1, 0.75) if stats: stats.WillChangeNotification(StatTypes.Stat.CTR).connect(OnStatCounterWillChange) turnController = Global.battleController.turnOrderController turnController.turnCheckNotification.connect(OnTurnCheck) func _exit_tree(): unit.scale = Vector3.ONE stats.WillChangeNotification(StatTypes.Stat.CTR).disconnect(OnStatCounterWillChange) turnController.turnCheckNotification.disconnect(OnTurnCheck) func OnTurnCheck(target:Unit, exc:BaseException): if unit == target: if exc.defaultToggle == true: exc.FlipToggle() func OnStatCounterWillChange(sender:Stats, vce:ValueChangeException): if unit == sender.get_parent(): if vce._toValue > vce._fromValue: vce.FlipToggle()
Since we are messing with the BaseException default toggle, it might be a good idea to make things a little safer as we don’t want other classes changing it directly. Godot doesn’t have private variables, but having a separate variable using “_” prefacing it will at least indicate that we should be cautious using it outside the class.
In BaseException.gd we’ll modify the script as follows
extends Node class_name BaseException var toggle:bool var defaultToggle:bool: get: return _defaultToggle var _defaultToggle:bool func _init(default:bool): _defaultToggle = default toggle = _defaultToggle func FlipToggle(): toggle = !_defaultToggle
Stat Comparison Condition
Other status effects might only last a few turns, but for KO, we want the status to last as long as the unit has zero HP. So we’ll create a new condition that will watch the unit’s HP value and remain in effect so long as HP is zero. However the condition will also be able to watch other stats, and check for other values than just zero. Maybe you want a walk on water status if you have a speed over 90. Or maybe a berserks status that lasts while the units health is below 10%.
The script is fairly simple. We hold several variables for the stat we want to watch, and the value to watch for. We also include a variable to hold a function that we’ll call to do the actual comparison. We’ve included several comparison functions that will cover the primary uses, but you could also pass in a different function if need be.
We set the values, and connect a signal to watch the stats in the Setup() function. When we receive a signal that stats have changed, we’ll check to see if our condition is still valid, and if not we’ll remove the status.
In the folder “Scripts->View Model Component->Status->Conditions”, create a new script named “StatComparisonCondition”
extends StatusCondition class_name StatComparisonCondition var type:StatTypes.Stat var value:int var condition:Callable var stats:Stats func _ready(): stats = Global.GetParentUnit(self).stats func Setup(type:StatTypes.Stat, value:int, condition:Callable): self.type = type self.value = value self.condition = condition stats.DidChangeNotification(type).connect(OnStatChanged) func EqualTo (): return stats.GetStat(type) == value func LessThan (): return stats.GetStat(type) < value func LessThanOrEqualTo (): return stats.GetStat(type) <= value func GreaterThan (): return stats.GetStat(type) > value func GreaterThanOrEqualTo (): return stats.GetStat(type) >= value func OnStatChanged(sender:Stats, oldValue:int): if condition != null && !condition.call(): Remove()
Auto Status Controller
We need some way to actually apply the KO status once a unit’s HP drops to zero. There are a couple ways we could do this. I think a really solid choice would be to add this to a units “Status” script, as it is already in charge of adding and removing status effects. Another option is to create a controller that watches all units for changes and applies the effect on them once it sees a unit’s HP dropping to zero.
The original tutorial went with the second option, which this time I’ll go with as well, although in our case it would perhaps have been simpler to go with the first option due to how our status and signals are set up, which are slightly different than what the Unity version uses. To make the second option work, we need to first watch for any changes to the unit array on the battle controller, so we can connect to each individual unit’s stat signal. I would have just avoided going through that extra trouble if another script further in the lesson didn’t need the exact same setup, which is why I decided to go ahead and keep with the original setup.
We don’t have the signals on the battle controller yet, but we’ll add them shortly. In _enter_tree() we’ll watch for those unit changes and when a unit is added or removed, we update our signals.
Once the signals are set up, whenever a unit’s HP stat changed we call “OnHPDidChangeNotification()” which will check the HP value and apply the status.
In the folder “Scripts->Controller”, create a new script named “AutoStatusController.gd”
extends Node class_name AutoStatusController func _enter_tree(): Global.battleController.unitAdded.connect(UnitAdded) Global.battleController.unitRemoved.connect(UnitAdded) func _exit_tree(): Global.battleController.unitAdded.disconnect(UnitAdded) Global.battleController.unitRemoved.disconnect(UnitAdded) func UnitAdded(unit:Unit): unit.stats.DidChangeNotification(StatTypes.Stat.HP).connect(OnHPDidChangeNotification) func UnitRemoved(unit:Unit): unit.stats.DidChangeNotification(StatTypes.Stat.HP).disconnect(OnHPDidChangeNotification) func OnHPDidChangeNotification(stats:Stats, oldValue:int): var status:Status = Global.GetParentUnit(stats).status if(stats.GetStat(StatTypes.Stat.HP) == 0): var condition:StatComparisonCondition condition = status.Add(KnockOutStatusEffect, StatComparisonCondition, "Knockout Status Effect", "Stat Comparison Condition") condition.Setup(StatTypes.Stat.HP, 0, condition.EqualTo)
Battle Controller
Open the script “BattleController.gd”
Lets start by adding our signal variables toward the top of the script with the other variables.
signal unitAdded(unit:Unit) signal unitRemoved(unit:Unit)
Next we need a variable to hold our Auto Status Controller
@export var autoStatusController:AutoStatusController
And last, in order to know when units are added or removed, we need to control how they are added. We’ll do this by creating a private variable to hold the actual list of units, and our original “units” variable will just be able to get it, but not set. We’ll then add two functions to add and remove units that include an emit for our signals. So replace our original line “var units:Array[Unit] = []” with the following
var units:Array[Unit]: get: return _units var _units:Array[Unit] = [] func AddUnit(unit:Unit): _units.append(unit) unitAdded.emit(unit) func RemoveUnit(unit:Unit): if _units.has(unit): unitRemoved.emit(unit) _units.erase(unit) unit.queue_free()
That script is done for now, but we created another problem, we broke how units are created. Luckily that all happens in one place for now. Open up InitBattleState.gd and in the SpawnTestUnits() function, replace the line “units.append(unit)” with the following
_owner.AddUnit(unit)
Next we need to update our Battle scene. Create a new node under “Battle Controller” named “Auto Status Controller” and attach “AutoStatusController.gd” script we just created. In the inspector for the “Battle Controller” node, assign the Auto Status Controller node to its respective variable.
With all that done we should be able to test our scene again. This time we should see a unit squash flat if it dies, or regain it’s shape if it recovers.
Health
We mentioned previously that there could be a use for having a minimum HP other than zero. We’ll set that up this time so that we can have a “leader” unit to defeat that will survive to fight again.
Open up “Health.gd”. We’ll start by adding a variable to the top
@export var minHP:int = 0
Then in OnHPWillChange() we need to change the function to use “minHP” instead of “0”
vce.AddModifier(ClampValueModifier.new(999999, minHP, MHP))
And we need to do the same for the clamp() function in OnMHPDidChange()
HP = clamp(HP, minHP, MHP)
Base Victory Condition
Now that we’ve laid a bit of groundwork, and have actual enemies on the field, its time we start to set up our actual victory conditions.
We’ll start by creating a base class. We won’t actually be attaching this directly. In Unity it would be marked as abstract, but Godot 4.1 doesn’t have abstract classes, though in later version that is a possibility.
There are many different battle conditions we could have for any given battle. Do you Defeat all enemies? Do you just have to survive a certain number of turns? Defeat a specific unit? Or maybe you have to find the treasure chest in the center of the vault and make your way to the escape route.
In the folder “Scripts->Controller” create a new folder named “Victory Conditions” and in that folder, create a new script named, “BaseVictoryCondition.gd”
We start the script giving it a class_name, which we’ll need when we inherit from it. We also create a variable to hold our battle controller, and another to keep track of whether we have a winner.
extends Node class_name BaseVictoryCondition var battle:BattleController var victor:AllianceType.Alliances: get: return _victor var _victor:AllianceType.Alliances = AllianceType.Alliances.None
In _enter_tree() we set the battle variable and listen to the unitAdded and unitRemoved signals. However unlike last time, this script may run after we spawn our units, so in order to make sure we don’t miss any units, we also check if the battle controller has any units added. If there are units in the array already, we manually add signals to them.
We’ll be watching the HP stat on all the units in our scene, and whenever the value changes, we check for game over conditions. This could be handled with more specific signals such as a unit’s death, but for what we are doing it shouldn’t add much overhead.
func _enter_tree(): battle = Global.battleController if battle.units.size() > 0: for unit in battle.units: UnitAdded(unit) battle.unitAdded.connect(UnitAdded) battle.unitRemoved.connect(UnitAdded) func _exit_tree(): battle.unitAdded.disconnect(UnitAdded) battle.unitRemoved.disconnect(UnitAdded) func UnitAdded(unit:Unit): unit.stats.DidChangeNotification(StatTypes.Stat.HP).connect(OnHPDidChangeNotification) func UnitRemoved(unit:Unit): unit.stats.DidChangeNotification(StatTypes.Stat.HP).disconnect(OnHPDidChangeNotification) func OnHPDidChangeNotification(stats:Stats, oldValue:int): CheckForGameOver()
In this base victory condition, CheckForGameOver() will only be checking for whether the heroes party has been defeated. The base condition doesn’t know what winning is, but we do at least know that losing your team will always be a loss.
We’ll be using PartyDefeated() to check in other victory conditions, so we have the alliance type in the parameters so we can check any specific team for defeat. As we loop through, if we find any single unit that is not defeated, we return that the team has not fallen yet.
func CheckForGameOver():
if(PartyDefeated(AllianceType.Alliances.Hero)):
_victor = AllianceType.Alliances.Enemy
func PartyDefeated(type:AllianceType.Alliances):
for unit in battle.units:
var alliance = unit.alliance
if alliance == null:
print("Alliance Null")
continue
if(alliance.type == type && !IsDeafeated(unit)):
return false
return true
func IsDeafeated(unit:Unit):
if unit.health:
return unit.health.minHP == unit.health.HP
return unit.stats.GetStat(StatTypes.Stat.HP) == 0
Defeat All Enemies Victory Condition
In the same folder, “Scripts->Controller->Victory Conditions”, create a new script named “DefeatAllEnemiesVictoryCondition.gd”
In this one, we are just overriding CheckForGameOver(). We still want to check if the Hero team has been defeated, so we call super() to pass through the state from the base victory condition. We also add a check for if the victory is still set to “None” on the alliance, so that if the hero did lose, we don’t override it with a victory if they defeated the enemy at the same time or something.
extends BaseVictoryCondition class_name DefeatAllEnemiesVictoryCondition func CheckForGameOver(): super() if(victor == AllianceType.Alliances.None && PartyDefeated(AllianceType.Alliances.Enemy)): _victor = AllianceType.Alliances.Hero
Defeat Target Victory Condition
In the same folder, “Scripts->Controller->Victory Conditions”, create a new script named “DefeatTargetVictoryCondition.gd”
This one is similar to the previous, we check if the Hero team has lost and make sure the victory alliance is still “None”, but this time, instead of checking the entire team, we check whether just a single unit is defeated. We’ll have to be sure to set the unit in code once we’ve added the victory condition and the units to the scene.
extends BaseVictoryCondition class_name DefeatTargetVictoryCondition var target:Unit func CheckForGameOver(): super() if(victor == AllianceType.Alliances.None && IsDeafeated(target)): _victor = AllianceType.Alliances.Hero
Init Battle State
Open the script “InitBattleState.gd”
Because each battle may have its own victory condition, we wait to add it until we load our battle. For this example we’ll create a function to add a DefeatTargetVictoryCondition to our battle controller and set it to our variable on the Battle Controller.
We’ll start by grabbing the enemy unit we want to assign as the “boss”. In this case we use [-1] on the array position to grab the last unit in the array, which in the order we created the units would be the “Enemy Wizard”. We’ll us the enemy name to add the name to our victory condition node, so we know who we are trying to defeat.
Once we’ve created the node, and given it a name, we set its target value to the enemy we grabbed from the array. And to make it a little more bosslike, we set the minHP to 10, so that it isn’t truly defeated in this battle. Fleeing to fight us again later in the game.
We’ll add this function somewhere at the end of the script.
func AddVictoryCondition ():
var enemy:Unit = Global.battleController.units[-1]
var vc:DefeatTargetVictoryCondition = DefeatTargetVictoryCondition.new()
Global.battleController.add_child(vc)
vc.name = "Defeat {0} Victory Condition".format([enemy.name])
Global.battleController.victoryCondition = vc
vc.target = enemy
var health:Health = enemy.health
health.minHP = 10
Because we are grabbing an enemy from the scene to use in the setup of our victory condition, its important that we call this after the units have already been created. So, in the Init() function, just after we call “SpawnTestUnits()”, add the line
AddVictoryCondition()
Battle Controller
Before the previous script will be able to actually do anything, we need to create the variable in “BattleCotroller.gd” that it is trying to set. Add this to the top of the script with the other variables.
@export var victoryCondition:BaseVictoryCondition
Battle State
We’ll need to add a couple functions to the base, “BattleState.gd” script so that all of our battle states will have access to them. IsBattleOver() and DidPlayerWin() which we can use to test for victory conditions to determine what to transition to depending on the outcome.
func DidPlayerWin(): return _owner.victoryCondition.victor == AllianceType.Alliances.Hero func IsBattleOver(): return _owner.victoryCondition.victor != AllianceType.Alliances.None
Cut Scene State
When the battle is over, we’ll play short cutscene like we do in the intro. This time though, we’ll have two different possible outcomes, depending on whether you win or lose. In a final game, we wouldn’t hardcode this. Not all battles will have an end cutscene like this, and the scene itself will be different for each battle.
Open the script “CutSceneState.gd”
We’ll be making a few changes here. In the _ready() function, we’ll put off setting the cutscene to the data variable so we can delete that line. The only thing left in the function now is a call to super(), so we can actually delete the entire function, so long as you haven’t added anything else that you want to keep around.
Next, in the “Enter()” function, we’ll add an if block to decide which conversation we want to load.
func Enter():
super()
if IsBattleOver():
if DidPlayerWin():
data = load("res://Data/Conversations/OutroSceneWin.tres")
else:
data = load("res://Data/Conversations/OutroSceneLose.tres")
else:
data = load("res://Data/Conversations/IntroScene2.tres")
_owner.conversationController.Show(data)
Next, once the conversation is over, we’ll transition to a new “End Battle State”. In the OnCompleteConversation() function, we’ll add another if block to bring us to the new state if the battle is over.
func OnCompleteConversation(): if IsBattleOver(): _owner.stateMachine.ChangeState(endBattleState) else: _owner.stateMachine.ChangeState(selectUnitState)
To go along with that, we’ll also need to create a variable for the new battle state as well. At the top with the other variables add this as well
@export var endBattleState: State
Conversation Data
Before we move on to the endBattleState, lets create the conversation data for our two new outro scenes.
In the folder “Data->Conversations” create two new resources of custom type we created a while back, “ConversationData”. We’ll name them “OutroSceneLose.tres” and “OutroSceneWin.tres” respectively. I don’t have any translations for the lines this time.
Start by setting the array to the size matching the number of speakers. 3 for OutroSceneWin, and 1 for OutroSceneLose. Click on where it says “<empty>” and choose “New SpeakerData”
Next to where it says “Speaker” to get our avatar, click on this “<empty>” or the arrow to the side and choose “Load”. We are looking for are “Textures->UI->EvilAvatar.png” and “Textures->UI->Avatar.png” depending on whether you need the good or evil avatar.

End Battle State
In a final game we would want to have several states here. From showing battle results and tallying rewards, to moving on to the next part of the game, whether that be the next battle, another cutscene to advance the story, or the world map. For now though, we’ll just focus on restarting the battle. We can do that one of two ways, we can load the scene from the path, which makes sense if we want to potentially move on to the next level, or for demonstration, we could just reset the current scene.
In the folder “Scripts->Controller->Battle States” create a new script named “EndBattleState.gd”
extends BattleState
func Enter():
super()
get_tree().reload_current_scene()
#get_tree().change_scene_to_file("res://Scenes/Battle.tscn")
Next we need to create a node to attach the state to. In the Battle scene, under the node “State Machine” create a new node named “End Battle State” and attach the script to it. While we are in the Battle scene, select the node “Cut Scene State” and in the inspector assign the End Battle State node to its respective variable.
Perform Ability State
We’ll see most change in status after an ability is performed, so we need to add a couple checks to the “PerformAbilityState.gd” script. We could cause a win/loss, or a unit may have KO’d themself in the middle of an attack and should no longer be able to continue making attacks.
We’ll start by adding a variable to hold two more States to go into.
@export var cutSceneState:BattleState @export var selectUnitState:BattleState
Then in the Animate() function, we add those checks to determine which state to go into.
func Animate(): #TODO play animations, etc ApplyAbility() if IsBattleOver(): _owner.stateMachine.ChangeState(cutSceneState) elif !UnitHasControl(): _owner.stateMachine.ChangeState(selectUnitState) elif(turn.hasUnitMoved): _owner.stateMachine.ChangeState(endFacingState) else: _owner.stateMachine.ChangeState(commandSelectionState)
Next we need to implement the UnitHasControl() function to determine whether a unit should be able to continue moving. At the moment KO is the only thing that would prevent that, but in the future as we add more to our game, we might set up something to watch for other possibilities.
func UnitHasControl(): return Global.GetChildOfType(turn.actor.status, KnockOutStatusEffect) == null
All that is left there now is to assign the two new State variables in the inspector to their respective nodes. Once you have that, we should be able to have a complete battle and have it restart.
Stat Panel
Now that we have everything we need for victory conditions up and running, the only thing left for this lesson is a couple bits of polish. The first bit is actually setting the correct backgrounds for our attack panels. Previously they were just randomized to show different colors, but now that we have alliances, we can actually set them to their proper colors.
In the script “StatPanel.gd” in the “Display()” function, replace the temp line with the following
var alliance:Alliance = obj.alliance background.texture = enemyBackground if alliance.type == AllianceType.Alliances.Enemy else allyBackground
Facing Indicator
Another issue we had is that it is somewhat confusing what state we are in when we are supposed to choose a direction. To make that more clear, we’ll create a visual indicator to show what direction we are choosing.
We’ll start by creating the indicator itself. In the “Prefabs” folder, create a new scene of type “3D Scene” with the name “Facing Indicator.tscn”
As a child of the main root node in the prefab, create a new child node of type “MeshInstance3D” and in the inspector set the mesh to “New SphereMesh”. We’ll be duplicating this mesh, so for now we’ll just set the transform values that stay the same throughout. In the Node3D section under Transform, set the Y Position to 0.6, and set all three scale axes to 0.25.
Duplicate the node so you have 4 spheres and name them “South”, “East”, “North”, and “West”. We’ll use these values to fill in the X and Z positions.
| x | z | |
|---|---|---|
| South | 0 | 0.3 |
| East | 0.3 | 0 |
| North | 0 | -0.3 |
| West | -0.3 | 0 |
Next we need a new material to apply to the spheres for their default state. We’ll use “Selection.tres” material for the highlighted color. In the “Materials” folder duplicate the “Selection.tres” material and name it “Default.tres”
Open the material and under “Albedo” set the color to gray, such as “808080”
Next, lets create the script for the facing indicator. In the folder “Scripts->View Model Component” create a script named “FacingIndicator.gd”
The script itself is pretty simple. We store the two materials, and the sphere meshes. The SetDirection() function gets the direction, and sets the directions to their respective colors.
extends Node class_name FacingIndicator @export var directions:Array[MeshInstance3D] @export var normal:StandardMaterial3D @export var selected:StandardMaterial3D func SetDirection(dir:Directions.Dirs): for i in 4: var directionMaterial:StandardMaterial3D = selected if i == dir else normal directions[i].set_surface_override_material(0, directionMaterial)
Save the script and attach it to the root, “Facing Indicator” node of the Facing Indicator scene.
Select that root node, and in the inspector set the “Directions” array size to 4, and assign the spheres to the array. Because we’ll be using this to match the directions, we need to make sure they are in the correct order. “South”, “East”, “North” and “West”
We also need to set the color values. We’ll load the materials “Materials->Default.tres” and “Materials->Selection.tres” for the Normal and Selected variables.
Next we need to add a couple lines to the “BoardCreator.gd” script(or Board.gd if you are coming from the video versions).
At the top we need a couple variables. One will hold the prefab, and we’ll use the other to reference the object in the scene.
@export var facingIndicatorPrefab:PackedScene
var facingIndicator:FacingIndicator
In the _ready() function we need to add a few lines after we finish setting up the marker.
facingIndicator = facingIndicatorPrefab.instantiate() facingIndicator.visible = false marker.add_child(facingIndicator)
Save the script and in the Battle scene select the Board node and assign the “Facing Indicator.tscn” prefab to the variable “facingIndicatorPrefab” variable.
In the “BattleController.gd” script we need to add a reference to the Facing Indicator to access it more easily. At the top with the other variables, add
var facingIndicator:FacingIndicator: get: return board.facingIndicator
The last thing we need to do is in the “EndFacingState.gd” script where we actually show the Facing Indicator and set the spheres to their correct colors. First we need to make them visible when we enter the state, and add and Exit() function so we can also hide them when we leave the state.
func Enter(): super() startDir = turn.actor.dir SelectTile(turn.actor.tile.pos) _owner.facingIndicator.visible = true _owner.facingIndicator.SetDirection(turn.actor.dir) func Exit(): _owner.facingIndicator.visible = false super()
The last thing we need is to update the spheres when we switch directions. In the “OnMove()” function, at the end add the line
_owner.facingIndicator.SetDirection(turn.actor.dir)
Directional Attacks
When using an attack with a directional based range, there a couple small issues. First, I’ll leave up to readers to fix, as its something we can safely get around. That is directional attacks should be paired with a FullAbilityArea. The reason here is that the targeting square stays centered on the character itself, which causes other area effects to have target the caster instead.
The next issue is that when selecting a direction with the directional attack, the secondary stat panel shows up. Again, because the target is the caster themself, it will incorrectly list the caster in the panel. This time, I’ll set it up so the secondary panel doesn’t show up in this phase until after we choose a direction and we have a list of units that are targets.
In the script AbilityTargetState.gd in the function Enter(), comment out, or remove the following lines. I’m not sure what the correct behavior should be here. Instead of removing it, we may want to instead negate it with “!ar.directionOriented” so that it doesn’t highlight the caster twice on directional attacks, but then in non directional attacks it starts out highlighting the caster twice because the unit and the initial cursor positions are the same. It does this anyway when we move the cursor back to the caster, so maybe that is the correct behavior. I’ll leave that up to you to decide.
if(ar.directionOriented): RefreshSecondaryStatPanel(pos)
BoardCreator
While we are making tweaks, Let’s rename the tiles to use their coordinates, so that they aren’t all random node names. I updated this in the video, and I think it would make sense to add this in the written versions as well. If we ever run into an issue involving the tiles, it will be useful for them to have names to more quickly isolate the problem.
In the script “BoardCreator.gd” there are three functions that need a line added to them _get_or_create(), loadMap(), and loadMapJSON(). The line needed to add to each of them is slightly different for each, but the code will be added just after the line “var t: Tile = _Create()” in all three of them.
In _get_or_create() just after the line “var t: Tile = _Create()”
t.name = "Tile_{0}_{1}".format([p.x, p.y])
In LoadMap() just after the line “var t: Tile = _Create()”
t.name = "Tile_{0}_{1}".format([save_x, save_z])
In LoadMapJSON() just after the line “var t: Tile = _Create()”
t.name = "Tile_{0}_{1}".format([mtile["pos_x"], mtile["pos_z"]])
Bugs
Before finishing up this lesson, thanks to a user, Birglendis, it’s been pointed out that I missed one of the pieces in the Magic lesson that allows the absorb skill to work. In the script “BaseAbilityEffect.gd” in the function “Apply()” we need to add a “self” as an additional parameter in the HitNotification.emit(), and MissedNotification.emit() sections.
hitController.HitNotification.emit(OnApply(target), self)
hitController.MissedNotification.emit(self)
Demo
That’s the last of the changes for this lesson. There was a lot to cover here, especially with the addition of the refactor. Go ahead and test out the last changes we made and see how the Facing indicators and panel colors look.
Summary
This was a long lesson, but we covered a lot and I think some of the changes will make things easier going forward, and we’ve got a battle that feels much more like a battle now. We have a visual indication of when units fall, and something plays out when the battle is over.
If you have any questions feel free to ask in the comments below, check out the Github repository to compare your code, or find me on Discord. I’ve broken the repository for this lesson into two commits to keep all the refactor code separate so it will be easier to follow.