Using a function to make an instance of the node that called.

I’m making a globally callable text engine kind of like Undertale’s, which can be called from any node. I made a global script so I could make a function that any node could access so I only have to make the function once and just call it. The problem is I can’t figure out a way to add the text instance to a different node. I think if I can get the path it would work, however I can’t get the add_child property to work on any variable types.

Right now my code looks like this:

func textGen(text: String, path: NodePath):
	var instance = TextEngine.instantiate()
	TextEngine.text = text
	path.add_child(instance)

I tried making the path variable a node however I’m pretty sure it actually just makes a node rather than get the path of it.

Hi,

add_child cannot work on “any variable type” as it belongs to the Node class. You could try to retrieve a node from a path and then add a child to that node, however, I’m wondering why you’re using a path although a node variable would work?

func textGen(text: String, node: Node):
	var instance = TextEngine.instantiate()
	TextEngine.text = text
	node.add_child(instance)

You can then use paths before calling that functions, of course. But if the function itself only needs a node to add a child to it, then you should simply use a node as an argument.

Another way would be to return the instantiated text, so that you can use it in any way you want based on the current context, like this:

func textGen(text: String) -> TextEngine:
	var instance = TextEngine.instantiate()
	TextEngine.text = text
	return instance

I may have misunderstood something so feel free to tell if that doesn’t help.


Also, I’m wondering why you’re changing the text property inside the TextEngine class, after creating a text instance?
Usually, such a function would look like this:

var instance = TextEngine.instantiate()
instance.text = text

Is this an intended behaviour?

Thanks for answering first of all. Pretty new to godot so I’m very inexperienced.

To answer your first question, I thought making the variable a node variable would make a new node, rather than store a node’s path.
The reason I’m not returning instance but making it inside the function is so I don’t have to create a child over and over. It’s mainly a preference.

And to answer your third, I don’t even know. Now I will mention that since I am a new account it took a while for the post to be approved, and I basically figured out everything you said while I had to wait.

Despite it I appreciate you confirming everything and I do apologize I didn’t delete this post before it was approved or edit it, I just couldn’t figure out a way to, as this is my first experience with Godot forums.

1 Like

Don’t worry, even though you already had figured things out, this forum can also help other people in need. Maybe someone will read that topic in 3 years and find an answer to their problem :laughing:

1 Like