I’m trying to instantiate a Scene and call a function (setColor) from a script (Field.gd) attached to the root node of the scene. Here’s a simplified version of my code:
extends Control
var field: PackedScene = load("res://GUI/field.tscn")
# Called when the node enters the scene tree for the first time.
func _ready():
if field == null:
print("Failed to load PackedScene")
return
var fieldInstance = field.instantiate()
fieldInstance.setColor(Color.BLACK) # Call setColor function
The setColor function is defined in Field.gd like this:
extends Control
func setColor(color):
# Color setting logic here
When I run the code, I get the error “Invalid call. Nonexistent function ‘setColor’ in base ‘Control’”. This suggests that the setColor function is not found in fieldInstance.
I’ve checked that the Field.gd script is attached to the root node of the field.tscn scene, and that the function name matches exactly. I’ve also tried printing the type of fieldInstance, and it prints 24 and True for fieldInstance is Control.
I’m using Godot 4.1.3. Any help would be appreciated.
A shot in the dark here.
I see you have the _init() function declared, but you didn’t provide a default value for color. Try giving it a default value. Eg:
It should’ve printed a warning for this in the bottom dock, right?
Because that means that Godot couldn’t construct an instance properly and just skipped the attached script.
I’ve helped a few others address this problem in the Discord as well and they never got an error either. I do agree that it should throw an error, but I’ve yet to see it happen.
Randomly stumbled into this thread and found a solution to a problem I’ve also had a few times lately and nobody seemed to know the answer to. Can confirm I never received an error, it was most mysterious. Thank you for this!