Why are some LocalScript actions not localized?

The following LocalScript changes a door so that the keycard holder can pass through it. But these changes are visible to all the players when I want them to be visible to only the local player. Any idea why this isn’t working the way I expect?

local COOLDOWN = 3

for _, door in ipairs(workspace.Doors:GetChildren()) do
	local debounce = false
	door.Touched:Connect(function(hit)
		if debounce then
			return
		end
		debounce = true
		if hit.Parent.Name == door:GetAttribute("KeyName") then
			door.Transparency = 0.5
			door.CanCollide = false
			task.wait(COOLDOWN)
			door.Transparency = 0
			door.CanCollide = true
		end
		debounce = false
	end)
end

I’m going to assume you’re putting this code in everyones client. Here is what’s going on:

  1. Player X touches the door with a part that has the KeyName attribute.
  2. Because the code is also on everyone elses client, they are also checking if there was ANY part with the attribute KeyName that was hit. Not just the one that the player themselves own.
  3. So because there is a part that hit the door with that attribute, the code fires on everyones client, and the door opens.

A way to solve this is checking if the player who touched the door with the keycard, is the same player running the code. If its not, then return out of the loop.

1 Like

I’m not sure I understand you. The code in question is a LocalScript in StarterPlayerScripts. Can you show me a short example of the solution you described?

Localscripts get copied to EVERYONES computer. And because you are detecting whether a part is touching another part, whenever that is true, the code runs on everyones computer and opens for everyone. You need to add another if statement to check if the person who is opening the door, is the same person who is running the code on their own side

1 Like

Okay, I understand now. Here is the final code. Thank you for your help.

local Players = game:GetService("Players")

local player = Players.LocalPlayer

local COOLDOWN = 3

for _, door in ipairs(workspace.Doors:GetChildren()) do
	local debounce = false
	door.Touched:Connect(function(hit)
		if debounce then
			return
		end
		debounce = true
		if hit.Parent.Name == door:GetAttribute("KeyName") then
			-- Only the key holder can pass through the door.
			if Players:GetPlayerFromCharacter(hit.Parent.Parent) == player then
				door.Transparency = 0.5
				door.CanCollide = false
				task.wait(COOLDOWN)
				door.Transparency = 0
				door.CanCollide = true
			end
		end
		debounce = false
	end)
end
1 Like