1
votes

I am new to Godot I was working around with TPS demo of Godot. I was trying to modify the enemy script so that when all enemies are dead it automatically takes to main menu. Here is what I did Initialized a variable

var asf=1

than inside hit function

func hit():
    if dead:
        if asf==5:
            get_tree().change_scene("res://menu/menu.tscn")
        return
    animation_tree["parameters/hit" + str(randi() % 3 + 1) + "/active"] = true
    hit_sound.play()
    health -= 1
    if health == 0:
        dead = true
        asf+=1
        //and so on

But it is not working and when I tried moving down and removing if condition as soon as level loads it goes back to main menu see this:

func hit():
    if dead:
        return
    animation_tree["parameters/hit" + str(randi() % 3 + 1) + "/active"] = true
    hit_sound.play()
    health -= 1
    if health == 0:
        dead = true
        asf+=1
        //and so on
        get_tree().change_scene("res://menu/menu.tscn")
1

1 Answers

1
votes

GDScript has no static (a.k.a shared) variables. And thus, you have an instance of the variable per enemy. If anything, the variable only ever gets to 1, because the enemy it is on can only die once.

Instead, add signals on the enemies. Signals they can emit when they die. See Custom signals.

For example:

signal died

# ...

func hit():
    # ...
    if health == 0:
        dead = true
        emit_signal("died")

You can then have a node dedicate to keep track of how many enemies died. Connect the signal to that node (either from the IDE, or from GDScript with connect). Every time it gets the signal you update the count, and change scene when appropriate.