In-game console

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By VarionDrakon

Hello, guys, who knows how to implement an in-game console in Your project? Example of consoles: Skyrim, CS, etc.

:bust_in_silhouette: Reply From: klaas

Hi,
this is my approach:

if have a container with a LineEdit in it. Output is debugger console but can be easly changed

extends LineEdit
class_name Console

var objects:Dictionary
var open:bool = false

func _ready():
	app.console = self


func register( object ):
	objects[object.name] = object


func _input(event):
	if event.is_action_pressed("ACTION_CONSOLE"):
		if open:
			close()
		else:
			open()


func open():
	open = true
	app.disable_actions = true
	get_parent().visible = true
	get_parent().get_parent().visible = true
	grab_focus()
	Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)


func close():
	open = false
	app.disable_actions = false
	get_parent().visible = false
	get_parent().get_parent().visible = false
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func _on_TextEdit_text_entered(new_text:String):
	close()
	
	print("Console: "+new_text)
	var parts:PoolStringArray = new_text.split(" ", false )
	
	text = ""
	
	var cmd
	var objectName
	var attributes
	
	if parts.size() == 0:
		return
	if parts.size() > 0:
		cmd = parts[0]
		cmd = "cmd_"+cmd.trim_prefix("_")
		parts.remove(0)
	if parts.size() > 0:
		objectName = parts[0]
		parts.remove(0)
	if parts.size() > 0:
		attributes = parts
	
	if has_method(cmd):
		# first try to call local
		call(cmd,objectName,attributes)
	else:
		#then try to call on object
		call_on_object( cmd, objectName, attributes )


func call_on_object( cmd, objectName, attributes ):
	if not objects.has(objectName):
		print("Console: object unknown")
		return
	
	var object = objects[objectName]
	
	if object.has_method( cmd ):
		object.call(cmd, attributes)
	else:
		print("Console: methode unknown")
		return

#------------------- list of commands avail

func cmd_get_names(objectName, attributes):
	for name in objects:
		print( name )

while app is a singleton is use to store objects globaly.

Since i want to address functions in objects … objects have to register with

app.console.register(self)

i disable all other inputs like WASD movement here. You have to implement this in your _inputs

app.disable_actions = true

all my commands get prefixed with “cmd_” to keep user from accessing other functions
the console first tries to call the command localy when there is no local function it then tries to call it on the object of the given name

Yeah, “I see.”… Thanks…

VarionDrakon | 2020-10-04 18:56

:bust_in_silhouette: Reply From: Bernard Cloutier

I haven’t tried it yet, but there is one in the asset lib: In-game console - Godot Asset Library