You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Godot中如何通过单个脚本执行其他外部脚本

GDScript 实现执行外部脚本的方案

你要的类似Python exec(open("file.py").read())的效果,在GDScript里可以按两种场景实现:


场景1:调用提前写好的固定脚本(绝大多数场景推荐)

这是Godot最常用的脚本调用方式,性能更高也更稳定:

  • 首先给你要调用的目标脚本添加类名声明,比如你的目标脚本路径是res://game_start.gd,在脚本第一行加如下代码:
# extends后面的父类根据你的脚本实际用途调整即可
class_name GameStart extends Node

func run():
    # 这里写你要执行的游戏启动逻辑
    print("游戏开始逻辑运行")
    get_tree().change_scene_to_file("res://main_game.tscn")
  • 然后在按钮绑定的触发函数里直接调用即可:
func _on_start_button_pressed() -> void:
    # 直接调用自定义类的方法
    GameStart.run()

场景2:动态执行外部脚本文件内容(完全匹配你给出的Python代码效果)

如果你确实需要运行时动态读取并执行外部gd脚本的内容,可以用以下方法:

# 适用于Godot 4.x版本,Godot 3.x请把FileAccess替换为File
func exec_gd_file(file_path: String) -> void:
    # 读取脚本文件内容
    var file = FileAccess.open(file_path, FileAccess.READ)
    if not file:
        print("文件读取失败,错误:", FileAccess.get_open_error())
        return
    var script_content = file.get_as_text()
    file.close()

    # 动态加载并执行脚本
    var dynamic_script = GDScript.new()
    dynamic_script.source_code = script_content
    var load_res = dynamic_script.reload()
    if load_res != OK:
        print("脚本加载失败,错误码:", load_res)
        return
    # 实例化后脚本的_ready函数会自动执行,也可以主动调用脚本内的其他方法
    var instance = dynamic_script.new()
    add_child(instance)

调用示例:

func _on_start_button_pressed() -> void:
    exec_gd_file("res://your_target_script.gd")

注意:动态执行外部未知脚本存在安全风险,如果你的游戏要对外发布,不要随意执行用户上传的第三方脚本。

内容的提问来源于stack exchange,提问作者RockZombie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:24:01