Godot Version
4.5
ive been trying to make a scene switch for ages and i followed a tutorial (https://www.youtube.com/watch?v=sKqtCc_HykM) but when i was trying to get the player to appear in the scene that we switched to (like a top down rpg room switch) but it just gives me “Invalid access to property or key ‘player’ on a base object of type ‘Node2D’.” everytime i enter the door. My scene_manager code is this
class_name SceneManager extends Node
var player: Player
var scene_dir_path = "res://scenes/"
func change_scene(from, to_scene_name: String) -> void:
player = from.player
player.get_parent().remove_child(player)
var full_path = scene_dir_path + to_scene_name + ".tscn"
from.get_tree().call_deferred("change_scene_to_file", full_path)
my player code is this
class_name Player extends CharacterBody2D
@export var speed = 200.0
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var attack_timer: Timer = $attackTimer
var can_attack : bool = true
func _physics_process(delta: float) -> void:
var input_direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
if animation_player.is_playing() and animation_player.current_animation == "slash":
velocity = Vector2.ZERO
move_and_slide()
return
if input_direction != Vector2.ZERO:
velocity = input_direction * speed
else:
velocity = Vector2.ZERO
move_and_slide()
if Input.is_action_just_pressed("sword") and can_attack == true:
can_attack = false
attack_timer.start()
animation_player.play("slash")
func _on_attack_timer_timeout() -> void:
can_attack = true
func _on_sword_area_entered(area: Area2D) -> void:
if area.is_in_group("enemy_hurt_box") and area.has_method("take_damage"):
area.take_damage(10)
if area.is_in_group("enemy_hurt_box"):
var enemy = area.get_parent()
if enemy.has_method("take_damage"):
enemy.take_knockback(global_position, 45)
if area.is_in_group("breakable_projectile") and area.has_method("destroy"):
area.destroy()
move_and_slide()
my door code is this
class_name SceneTrigger extends Area2D
@export var connected_scene : String #name of scene we want to change to
var scene_folder = "res://scenes/"
func _on_body_entered(body: Node2D) -> void:
if body is Player:
scene_manager.change_scene(get_owner(), connected_scene)
and my scene i want to change to code is this
extends TileMapLayer
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
if scene_manager.player:
add_child(scene_manager.player)