Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Howcome this script works is studio but not in the real game?

Asked by 7 years ago
function func()
    wait(1)
    local plr = game.Players.LocalPlayer
    local gear = game.ReplicatedStorage:WaitForChild("DecoyDeploy")
    gear:Clone().Parent = plr.Backpack
    gear:Clone().Parent = plr.StarterGear
    wait(1)
end
script.Parent.Touched:connect(func)

For some weird reason, this only works in studio and not in the real game.

1 answer

Log in to vote
3
Answered by
Discern 1007 Moderation Voter
7 years ago
Edited 7 years ago

You are attempting to use LocalPlayer in what I assume is a regular Script (not a LocalScript) that is in a part somewhere in Workspace. LocalPlayer only works in LocalScripts that are somewhere in the player, so LocalPlayer is not an option for this script.

The solution is to use the function GetPlayerFromCharacter(character). This returns the player associated with the character in the parameters, or nil if there is no character.

function func(partTouched) --partTouched is the part that touched.
    wait(1)
    local character = partTouched.Parent -The part that touched's parent would be the character if a body part is what touched.
    local plr = game.Players:GetPlayerFromCharacter(character) --Gets the player linked to the character.
    if plr then --Checks if there is actually a player
    local gear = game.ReplicatedStorage:WaitForChild("DecoyDeploy")
    gear:Clone().Parent = plr.Backpack
    gear:Clone().Parent = plr.StarterGear
    wait(1)
    end
end
script.Parent.Touched:connect(func)

Here is the Wiki Page on GetPlayerFromCharacter.

Here is the Wiki Page on LocalPlayer.

Ad

Answer this question