Handling multiple instanced scenes with the same name

Godot Version

4.4.1

Question

I’m making a small cashier game in Godot 4 where I spawn multiple money objects (like bills) as RigidBody3D scenes. For example five.tscn, ten.tscn, etc.

The problem happens when there’s mulitple of the same bill. My code checks body.name when they’re inserted into the register, but it seems like it randomly fails or doesn’t detect them properly when duplicates exist as the name just comes up as “@RigidBody3D@2” or something similar. Is there a better way to identify each object if they’re the same scene and same name?

Here’s how I currently (try to) spawn bills:

func spawn_bill(bill_name: String, position: Vector3):
	
        # spawn in the bill
	var scene = load("res://scenes/money/" + bill_name + ".tscn")
	var bill = scene.instantiate()
	bill.set_name(bill_name)

        # set the position
	bill.global_position = position
	
	bill.rotation.y = randf_range(-90.1, 90.1)
	get_tree().current_scene.add_child(bill)

I wouldn’t use names to distinguish between nodes, exactly because of the problem your describing. Using node groups should do the trick in this case.

The name of the node. This name must be unique among the siblings (other child nodes from the same parent). When set to an existing sibling’s name, the node is automatically renamed.

The problem here is you are using the name of the node to act as an important part of the node’s logic. This doesn’t work when the node is instantiated multiple times under the same parent.

If this were my project I would approach this differently. I would create a single bill.tscn that has a custom set_bill_value(bill_name: String) function to be called in place of your bill.set_name(bill_name). The set_bill_value function would then be responsible for configuring everything for the assigned bill name. Imagine the following:

class_name Bill extends RigidBody3D

var bill_value: String

func set_bill_value(bill_name: String):
    bill_value = bill_name
    # match bill_name:
    #    "Five":
    #        Sprite3D.texture = <texture for Five>
    #    "Ten":
    #        Sprite3D.texture = <texture for Ten>
    # etc.. or any other custom configuration needed for each bill

Then your register code can simply check for the bill_value to see what it is.

1 Like

Thanks this fixed it!

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