Search code examples
game-physicsgodotgdscript

Why isn't my timer in godot returning to 0?


extends Node

onready var box_container: BoxContainer = $VBoxContainer
var stage = 0 setget on_stage_change
var timer = 0.0



func on_stage_change(new_value):
    if new_value > 5:
        stage = 5
    else:
        stage = new_value


func _process(delta):   
    if stage > 5:
        return
    var file: Dictionary = loadjson()
    handle_message(file, timer)
    if timer == 0.0:
        print("corrent")
    timer += delta
    
    

func handle_message(file: Dictionary, timer: float):
    #print(file)
    var json = file[String(stage)]
    
    if json["sender"] == "system":
        add_system_message(json["message"])
    elif json["sender"] == "boss":
        add_boss_message(json["message"], timer)
        print(timer) # is > 1
    else:
        print("currently not handled")
    
func add_boss_message(message: String, timer: float):
    #print(timer)
    var current_label = box_container.get_child(box_container.get_child_count()-1)
    if is_most_recent_message_typing() and timer > 1:
        current_label.text = message
        stage += 1
        timer = 0.0
        print(timer) #is zero
        #print(timer)
    elif not is_most_recent_message_typing():
        var label = Label.new()
        label.modulate = Color(1, 0, 0)
        label.text = "[typing]"
        box_container.add_child(label)
    print(timer) # is zero
        

func is_most_recent_message_typing():
    #timer = 0
    if box_container.get_child(box_container.get_child_count()-1).text == "[typing]":
        return true
    return false
    
func loadjson():
    var file: File = File.new()
    file.open("Messages.json", File.READ)
        
    var json_file = parse_json(file.get_as_text())
    #print(json_file)
    return json_file

func add_system_message(message: String):
    var label = Label.new()
    label.text = message
    label.modulate = Color(1, 0, 0)
    box_container.add_child(label)
    stage += 1

for some reason my timer never returns to zero, despite me setting it. I have tracked the execution of the program, and found out that the timer resets to > 1 after the add_boss_message is executed.

Could someone please tell me why the variable isn't returning to 0

Using the latest stable version of godot on steam


Solution

  • UnholySheep gave the answer in a comment:

    timer inside add_boss_message is a local variable. It is not the same as the member variable timer of your script class. Why did you pass it as an argument to your functions instead of working on the member directly?