This is a script (Normal), it works very well. It’s a portal that unlocks with money. But when I put it in Local Script, it didn’t work, what can I do?
script.Parent.Touched:Connect(function(hit)
local player = hit.Parent:FindFirstChild("Humanoid")
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr.leaderstats.Coins.Value > 0 then
wait()
script.Disabled = true
script.Parent.Transparency = 1
script.Parent.CanCollide = false
script.Parent.SurfaceGui.Enabled = false
plr.leaderstats.Coins.Value = plr.leaderstats.Coins.Value - 5000
end
end)
LocalScripts will only run if they are a descendant of either:
A Player’s Backpack, such as a child of a Tool
A Player’s character model
A Player’s PlayerGui
A Player’s PlayerScripts.
The ReplicatedFirst service
Also, because leaderstat points are involved, some of your code logic must be done on the server, otherwise someone could cheat by spoofing the Coins value on their client. So to achieve the exact behavior you want there will have to be some server-client communication:
Server script inside the door:
script.Parent.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if (player and player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Coins") and player.leaderstats.Coins.Value >= 5000) then
game.ReplicatedStorage.DoorUnlock:FireClient(player, script.Parent)
player.leaderstats.Coins.Value = player.leaderstats.Coins.Value - 5000
end
end)
There should be a RemoteEvent in ReplicatedStorage named “DoorUnlock”
And a LocalScript in StarterPlayer.StarterPlayerScripts with this code:
local event = game.ReplicatedStorage:WaitForChild("DoorUnlock")
if (event) then
event.OnClientEvent:Connect(function(door)
door.Transparency = 0.5
door.CanCollide = false
end)
end
With this set up, when a player touches the door, it checks on the server that they have enough coins, subtracts the coins, then sends a signal to the client to open the door, and it will then only appear to be opened for that player.
You can keep your current script, but use collision groups to allow players to walk through the portal as @sjr04 suggested. A LocalScript is unnecessary in this case.