Godot Version
v4.3-stable
Question
The below is a snippet of code from a larger function turn() which simulates a player as an ai making moves in a turn-based strategy game by looping through all it’s pieces and making calculations. The player ai calculates it’s move, ability and attack and each of these has a 0.5 timer timeout, so that the moves don’t all happen at once.
func turn(...):
...
# ...'s are where I believe the code is not relevant.
if not is_instance_valid(unit): continue
print(unit.entity_name, " is trying to attack")
var calculated_attack = unit.ai.calculate_best_attack_options()
if calculated_attack != null:
unit.attack(calculated_attack[0], calculated_attack[1])
print(get_tree())
await get_tree().create_timer(0.5).timeout #Error occurs here
This code was all working fine until I added code that awaits dialogue finishing in a different script.
func level_specifics():
await handle_status_effects()
if player_turn == 2 && not ai.game_over:
await handle_dialogue()
show_actionables_for_player_turn()
#Simple function that shows some coloured circles for the current player's units.
# I've gutted this function to it's core for clarity purposes:
# The code that was here relates to the specific turns_played variable
# The error that occurs for me is on turn 6.5 which has no specific code here
await ai.turn(computer_buildings_entities.call(), player_units.call(), turns_played)
I have been doing my best to research this issue, googling etc. - I made sure to await other functions that come before ai.turn() which also use await. I also printed get_tree() and it returned a proper object as per my first code snippet.
I am not using onready variables as other people with similar issues have, additionally, I checked if using a longer wait period (5 seconds) would work to ensure that the timer was not timing out before I was accessing it.
Here is the some code in my handle_dialogue function which handles turn 6.5:
if turns_played == 6.5 and is_alive("goblin_slave") and is_alive("necromancer"):
dialogue.play_optional_dialogue("Montague_Kills_Grinkle")
await dialogue.finished_dialogue_set
grinkle.die()
if is_player_unit_in_grinkle_zone():
await player_is_spotted("necromancer")
Grinkle is a goblin unit on the npc’s side (as is Montague the necromancer). I have just thought of the theory that grinkle dying is the issue as my first snippet loops through all the units - however, this still confuses me as the error is occuring right after the necromancer is making an attack on an outpost and the error is on the timer and not at the start of the loop for the goblin unit (Grinkle).
Also apologies for the sphagetti code, have been a little depressed lately and have been struggling to code. Hopefully this question is clear and not annoying. Thanks in advance. Please let me know how I can help provide more information or if you want me to try something.