Script doesn't get node of an instancied scene

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


I’m new in Godot and have a problem that I can’t solve. I have a project where player 1 or player 2 play the same level not at the same time. So, in order to do that, I instanced my Player 1 or Player 2 scene to my level 1 (named "world2). It works, but know, my camera script that make follow the player only on the x axis doesn’t work anymore, because the camera is unable to find the node Player 1 or Player 2 (I get a null instance).

The scripts in my world scene look like that (for player2):

extends Node2D

onready var player2 = ("Root/world2/Player2")

func _ready():
   var Player2 = preload("res://Scènes/Player2.tscn").instance()

And the script of my camera 2D (was working before with the node player2 as a child of the world):

extends Camera2D

onready var player2 = get_node ("Player2")

func _process (delta):

    position.x = player2.position.x

I try to write also the absolute path of Player 2 but without success… Sorry if it’s a basic question but I can’t figure out =/…

:bust_in_silhouette: Reply From: StopNot

Hi there. First of all there’s a mistake in your script. This line:

onready var player2 = ("Root/world2/Player2")

The player2 variable is set to be a string. Looks like a path to the original node. Then in the _ready function you set the same variable again and you use preload to load the scene.

Try this way:

onready var player_two_scene = preload("res://Scènes/Player2.tscn")

func _ready():
    var player_two = player_two_scene.instance()

It would help if you provides the tree structure from your project.

EDIT: I see now that it’s not the same variable you set. Consider renaming the variables to avoid mistakes. Anyway my answer remains the same for now. :slight_smile: