Firing multiple times when it shouldn't

Godot Version

Replace this line with your Godot version

Question

i have 4 lightswitches in the scene but for some reason when i interact with one, it interacts with all of them at once

heres the code:

extends  MeshInstance3D

var camera: Camera3D
const RAY_LENGTH = 1000

func _ready():
	await get_tree().process_frame
	camera = get_viewport().get_camera_3d()

func _input(event):
	if event.is_action_pressed("Interact"):
		var mouse_pos = get_viewport().get_mouse_position()
		var from = camera.project_ray_origin(mouse_pos)
		var to = from + camera.project_ray_normal(mouse_pos) * RAY_LENGTH

		var space_state = get_world_3d().direct_space_state

		var query = PhysicsRayQueryParameters3D.create(from, to)
		query.collide_with_areas = true
		query.collide_with_bodies = true


		var result = space_state.intersect_ray(query)

		if result:
			var collider = result.collider.get_parent()
			if collider.name.begins_with("LightSwitch"):
				var linked_path = collider.get_meta("Linked")
				var linked = get_node(linked_path)

				var light1 = linked.get_node("LightFrame/SpotLight3D")
				var light2 = linked.get_node("LightFrame/SpotLight3D2")
				
				if collider.get_meta("Toggle") == true:
					light1.light_energy = 0
					light2.light_energy = 0
					collider.set_meta("Toggle", false)
				elif collider.get_meta("Toggle") == false:
					light1.light_energy = 0.545
					light2.light_energy = 0.235
					collider.set_meta("Toggle", true)

Are your light switches all sharing the same resource?

How did you determine that?

im so sorry for wasting ur time, the reason why is because each lightswitch has the script inside :sweat_smile:

So all of your light switches respond to _input and all of your light switches use the same raycast query (from player to what ever is in front of them) and all of these queries are resolved the same way (by node name begins with) so all of them flip.

Anywhere in that chain of events you need to pull a unique property from the node this switch is on. You could check for the exact name rather than a generic begins_with

if collider.name == self.name:
1 Like