Dynamic Script

Dynamic Script #

Godot game engine is very flexible. It allows, for example, to define a script in an external file, change it whenever you want and load or reload it dynamically in runtime.

The following example loads a script which draws 3 random rectangles. If you click to the screen, the script is reloaded from the text file and ran, so 3 other random rectangles appear.

Tip: Try to modify the drawing code in myscript.txt to draw e.g. 5 rectangles or do something else. Then just save the myscript.txt changes and click to the screen of the running app.

Dynamic Script in Godot

To replicate this example, create Node2D called Main and attach a script Main.gd. Then create a child Node2D and attached a script Node2D.gd. Finally, create a text file myscript.txt in the root folder of the Godot project.

Dynamic Script in Godot

The content of all 3 files is here:

extends Node2D

onready var file = 'res://myscript.txt'

# Called when the node enters the scene tree for the first time.
func _ready():
	reload()
	
func _input(event):
	if event is InputEventMouseButton:
		reload()

func reload():
#	var script = "extends Node\nfunc hw():\n\tprint(\"Hello World\")\n"
	var script = load_text_file(file)
	$Node2D.script.source_code = script
	$Node2D.script.reload(true)
	$Node2D.run()

func load_text_file(path):
	var f = File.new()
	var err = f.open(path, File.READ)
	if err != OK:
		printerr("Could not open file, error code ", err)
		return ""
	var text = f.get_as_text()
	f.close()
	return text
extends Node2D
extends Node2D

func run():
	update()		# force the _draw()

func _draw():
	draw_rect(rand_rect2(), rand_color(), 1, false)
	draw_rect(rand_rect2(), rand_color(), 1, false)
	draw_rect(rand_rect2(), rand_color(), 1, false)
	
# Helper to return random color
func rand_color():
	return Color(rand_range(0,1),rand_range(0,1),rand_range(0,1))

# Helper to return random rectangle 
func rand_rect2():
	return Rect2(
		rand_range(10, 580), rand_range(10,160), 
		rand_range(50, 150), rand_range(50, 150))	

You can download the whole zipped Godot project here: 100-DynamicScript.zip.