How to delete an object from another scene

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

I’ve a World scene with all the elements, one of them is an instance of a scene called “Bullet”, that has to delete one of the hearts that represent the lives every time that touches the player. ¿How can I delete them if it’s a different scene?

P.D: The script is not linked to the instance in the World scene, but in the scene’s root. This is because the code must be executed also by instances created by enemies.

What scene is the Heart in? I take it there is a parent scene that contains both the Heart and the World? I’m sure you can do what you want with signals but without the Node Tree it’s difficult to advise.

dacess123 | 2022-08-22 20:41

:bust_in_silhouette: Reply From: Wakatta


  • The scene must be in the scenetree


  1. Setup PhysicsBodies
  2. Get a reference to that scene using a nodepath
  3. Store that reference to a variable
  4. Remove node using reference


┖╴World (Node2D)
   ┠╴Bullet (Area)
   ┃  ┠╴Shape (CollisionShape2D)
   ┃  ┖╴Sprite (Sprite)
   ┠╴Enemy (KinematicBody2D)
   ┃  ┠╴Hearth (Sprite)
   ┃  ┖╴Gun (Sprite)
   ┖╴Player (KinematicBody2D)
       ┠╴Name (Label)
       ┠╴Hearth (Sprite)
       ┖╴Gun (Sprite)

func _ready():
    connect("body_entered", self, "_on_unit_hit")

func _on_unit_hit(body):
    #body will be player node or enemy node
    var heart = body.get_node("Heart")


You can get a reference to the node from root like this

var heart = get_node("/root/World/Enemy/Heart")

But that wont work in cases where you have multiple enemies

if you have multiple heart nodes on the Player/Enemy save them to a list
onready var hearts = [$Heart1, $Heart2, $Heart3]

and reference them like this

if not hearts.empty():
    var heart = hearts.pop_front()