How to instance new scenes with their attached scripts properly

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

In the script of Main scene (main.gd) I want to create instance of another scene (player scene), but player also have a player.gd script attached to player scene.

Problem:
In player scene script (player.gd), there are so many paths ($this, $that, $those, etc.), if I run player scene alone (by pressing F6) it runs correctly with all of those paths, but if Run the main scene (by pressing F5), those paths that are working in player scene are all NULL/nil.

Why? and how can I have some separated scenes with their own scripts and paths, and I just want to load that player inside my main scene.

:bust_in_silhouette: Reply From: Ertain

Try using the magic of NodePaths. When the game runs, those variables marked with the “$” operator are turned into NodePaths. Here’s a trick that I use which makes keeping track of those nodes easy.

Export a variable to the editor, and then assign that to a variable which is used by the script to stand in for the node.

# This places a widget in the Inspector of the editor which allows you to select the node in the scene tree.
export (NodePath) var some_node_path
onready var some_node = get_node(some_node_path)

func _ready():
    # Now use the variable in any part of the script.
    some_node.position = Vector2()

Hope this helps.