How can I change parameters and variables in one script from another script?

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

Let’s say I want to change some variable in Script A through Script B. I can use signals or

onready var nodeA = get_node("path/nodeA")
nodeA.varible = new_number

This method looks very good but seem to have a problem that it doesn’t work if node with Script B isn’t a parent of Script A or doesn’t exist in node path at all, so it starts to begin a problem if I have to make variable interectations through other node trees.
Is there any better way to change parameters and variables through code?

:bust_in_silhouette: Reply From: sirdorius
  1. How do you change variable in one script from another?
    Exactly how you described it. Get a reference to the node and simply set its property. There is no ‘better’ way to do it. So probably the more important question becomes:
  2. How do you get references to other nodes?
    This really depends on your specific situation. You could get it from a collision event, you could save it in your script in the editor, you could save it in a global singleton, you could use groups and call them with get_tree().get_nodes_in_group(). There are really too many ways to explain here.
  3. Should you change parameters in other scripts?
    Good programming practices dictate that you shouldn’t (encapsulation principle), and you should instead call functions of the target script instead of modifying its state directly.

Thanks, I think I’ve got a way to do and use this exactly as I want

TraitPhoe | 2023-06-15 19:05