How do I create a unique name for a node created in a script?

Godot Version

4.2.2

Question

For my project, I’m trying to create a simple rope-swinging type of thing in 2D where the rope can only swing on hooks. The way this works is complicated, but it essentially uses a RigidBody2D as the player, a StaticBody2D as the hook, and a PinJoint2D to get it to function. Unfortunately, I have a problem. But before I get into the specifics, here’s the main script of the project:

extends Node2D

@onready var rigidbody = $RigidBody2D
@onready var label = $UI/Label
@onready var line = $Line2D

var currentGrapplePath
var currentGrappleNode

func _ready(): 
	rigidbody.apply_impulse(Vector2(-300, 0))

func _process(delta):
	if Input.is_action_just_pressed("click") and global.hovering:
		global.grappling = true
		currentGrapplePath = global.hoveringOver
		currentGrappleNode = get_node(currentGrapplePath)
		
		var temp = PinJoint2D.new(); temp.name = "PinJoint2D"
		temp.node_a = currentGrapplePath
		temp.node_b = "/root/Main/RigidBody2D"
		currentGrappleNode.add_child(temp)
		line.visible = true
	
	if Input.is_action_just_released("click"):
		global.grappling = false
		currentGrappleNode.remove_child(%Help) # Path goes here...
		line.visible = false
	
	if rigidbody.global_position.y >= 650:
		rigidbody.global_position = Vector2(376, 0)
		rigidbody.linear_velocity = Vector2.ZERO
		rigidbody.apply_impulse(Vector2(-300, 0))

The problem is in this line of code:

currentGrappleNode.remove_child(%Help) # Path goes here...

The problem I have is that I want to assign a unique name to the PinJoint2D that is created in the script, but there doesn’t seem to be a clear way to do that. Does anyone know how to do this?

I’ll update this post if I find any solutions myself.

Are you certain you want to use remove_child()?
That function does not delete the node.
From your explanation, every time the player hooks the rope a new PinJoint2D is created, and from the code you are showing it never gets deleted.
This is a memory leak.

As to the original problem the parameter in remove_child() is looking for a node. It doesn’t necessarily need a node path.
If you keep your node in a class level variable you can just use that variable.

2 Likes

Thank you so much for the help! Just one thing to clarify, since you said that using remove_child is a memory leak, are you suggesting that I use something else like queue_free?

Yes, if you aren’t going to reuse that instance then free it.
Alternatively you could hide it and revive it as necessary, but you have a structure already that will work with queue_free()

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.