创建脚本模板

Godot 提供了一种在创建新脚本时使用脚本模板的方法, 在 脚本创建对话框 中可以看到:

../../_images/script_create_dialog_templates.png

默认提供一组默认脚本模板, 但也可以针对每个项目和编辑器修改现有脚本模板并创建新模板.

模板所在位置

有两个地方可以管理模板.

编辑器定义的模板

这些在任何项目中都可以全局使用. 这些模板的位置是根据操作系统而确定的:

  • Windows: %APPDATA%\Godot\script_templates\

  • Linux: $HOME/.config/godot/script_templates/

  • macOS: $HOME/Library/Application Support/Godot/script_templates/

如果未检测到 script_templates ,Godot将自动创建一组默认的内置模板. 在默认模板被意外覆盖的时候可以用这个方法重置.

项目定义的模板

搜索模板的默认路径是 res://script_templates/ 文件夹. 可以通过代码和编辑器在 项目设置 中配置 editor/script_templates_search_path 设置来更改路径.

如果在项目中未找到 script_templates 文件夹, 则将其忽略.

语言支持和重写行为

如果一个语言实现了根据模板生成脚本的方法, 你就可以创建一个对应拓展名的文件作为模板. 对于 GDScript 和 C#, 拓展名分别是 gdcs.

备注

脚本模板与常规脚本文件具有相同的扩展名。脚本解析器将这些模板视为项目中的实际脚本,这可能会导致问题。为了避免这种情况,创建空的 .gdignore 文件以忽略包含它的目录。该目录在整个项目的文件系统中不可见,但模板仍可以通过外部文本编辑器进行修改。

如果编辑器内置的模板与项目中创建的模板文件具有相同的文件名, 则内置的模板会被自动隐藏.

默认模板

默认 模板总是根据每种语言动态生成,并且不能配置也不能覆盖,但是你可以使用它们作为创建其他模板的基础。

GDScriptC#

  1. extends %BASE%
  2. # Declare member variables here. Examples:
  3. # var a%INT_TYPE% = 2
  4. # var b%STRING_TYPE% = "text"
  5. # Called when the node enters the scene tree for the first time.
  6. func _ready()%VOID_RETURN%:
  7. pass # Replace with function body.
  8. # Called every frame. 'delta' is the elapsed time since the previous frame.
  9. #func _process(delta%FLOAT_TYPE%)%VOID_RETURN%:
  10. # pass
  1. using Godot;
  2. using System;
  3. public class %CLASS% : %BASE%
  4. {
  5. // Declare member variables here. Examples:
  6. // private int a = 2;
  7. // private string b = "text";
  8. // Called when the node enters the scene tree for the first time.
  9. public override void _Ready()
  10. {
  11. }
  12. // // Called every frame. 'delta' is the elapsed time since the previous frame.
  13. // public override void _Process(float delta)
  14. // {
  15. //
  16. // }
  17. }

模板占位符

下面列出当前已实现的所有模板占位符.

基本占位符

占位符

描述

%CLASS%

新建类的名称(只在 C# 中使用).

%BASE%

新建脚本的基类型.

%TS%

缩进占位符. 缩进字符的类型和数量分别由 EditorSettings 中的 text_editor/indent/typetext_editor/indent/size 两个设置决定.

类型占位符

这些只在使用 GDScript 的静态类型时有用. 这些占位符是否被替换取决于 EditorSettings 中的 text_editor/completion/add_type_hints 设置.

占位符

%INT_TYPE%

: int

%STRING_TYPE%

:String

%FLOAT_TYPE%

: float

%VOID_RETURN%

-> void