当所有敌人都死了时,如何在 Godot 中改变场景?

How to change scene in Godot when all enemies are dead?

我是 Godot 的新手,我正在研究 Godot 的 TPS 演示。我试图修改敌人脚本,以便当所有敌人都死了时它会自动进入主菜单。 这是我所做的 初始化一个变量

var asf=1

比内部命中函数

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

但它不起作用,当我尝试向下移动并在关卡加载后立即删除 if 条件时,它会返回主菜单 看到这个:

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")

GDScript 没有静态(a.k.a 共享)变量。因此,每个敌人都有一个变量实例。如果有的话,变量只会达到 1,因为它所在的敌人只能死一次。

相反,向敌人添加信号。他们死后可以发出的信号。参见 Custom signals

例如:

signal died

# ...

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

然后您可以有一个节点专门用于跟踪有多少敌人死亡。将信号连接到该节点(来自 IDE,或来自带有 connect 的 GDScript)。每次收到信号时,您都会更新计数,并在适当的时候更改场景。