Can't set the script and input of script not works

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

Tried to set the script NOT works. I know it is hard but maybe s1 can be of help!

func _ready():
	get_node("/root/Node/Player").set_script(load("res://Scenes/Player/Player_fighter.gd"))

var MyClass = preload("res://Scenes/Player/Player_fighter.gd")
var instance = MyClass.new()
assert(instance.get_script() == MyClass)
print(get_node("/root/Node/Player"))

#	print(MyClass.)
#	assert(instance.set_script(load("res://Scenes/Player/Player_fighter.gd")))

_gui = preload("res://Scenes/Player/Player_fighter.gd")
_gui = _gui.new()
add_child(_gui)
:bust_in_silhouette: Reply From: njamster

When you post a question, please make sure that your code is formatted properly (each line has to start with 4 spaces, each additional 4 spaces equal an indentation layer). If you don’t, underscores are interpreted as markdown and indentation is lost, which makes your script a lot harder to read for others trying to help you.

Formatting aside your script is weird in many ways as well:

  1. print(MyClass.) will result in an “Expected identifier as member”-error
  2. assert(instance.setscript(...)) will always result in a failed assertion, because set_script is a void method, thus will never return true
  3. Also setting the script is pointless here, as the instance is created from that exact same script, thus has it already attached by default
  4. But it won’t work, as you never actually add instance to the tree
  5. _gui is not declared in the script you provided, thus will result in a 3rd error
  6. Otherwise it’s identical to instance, just that this time you add it to the tree
  7. It’s not clear why you sometimes use preload and sometimes load

So here’s a cleaned up version of your code:

const NODE_PATH = "/root/Node/Player"
const SCRIPT = preload("res://Scenes/Player/Player_fighter.gd")

func _ready():
    # works if NODE_PATH exists and the scriptpath is correct
	get_node(NODE_PATH).set_script(SCRIPT)

    # works, if you actually add it to the tree (third line)
	var MyClass = SCRIPT
	var instance = MyClass.new()
	add_child(instance)
    # is the same as the case before, just named differently
	var _gui = SCRIPT
	_gui = _gui.new()
	add_child(_gui)

Thanks User njamster - Godot Engine - Q&A. You saved me again. I owe you one. I have edited the code on my questions

Okan Ozdemir | 2020-06-28 20:30