I am trying to make a teleport to a tower so i want to remove the player (who steps on the pad)'s inventory. here is the code, I am using a regular script because when I use the same code in a local script, It doesnt work and I get no errors. The error i get here is
Workspace.Doors.Door4.Teleport.Clear Gear:2: attempt to index nil with 'Backpack'
This is my code.
1 | script.Parent.Touched:connect( function () |
2 | local p = game.Players.LocalPlayer.Backpack |
3 | p:ClearAllChildren() |
4 | end ) |
This means it's on a server script, you can't see the local player on the server.
Also connect
is deprecated, you should use Connect
.
We can use the Touched argument we name hit
which is the object that touched it. As an object can't be a Model
and a character is composed of a model with object parts, we can simply just check if the parent of the object is a player's character.
Solution script:
1 | local players = game.Players |
2 | script.Parent.Touched:Connect( function (hit) |
3 | local parent = hit.Parent |
4 | local playerGet = players:GetPlayerFromCharacter(parent) -- returns player or nil |
5 | if playerGet then -- is actually a player |
6 | playerGet.Backpack:ClearAllChildren() |
7 | end |
8 | end ) |
You cannot use LocalPlayer in a server script. Try this script instead:
1 | script.Parent.Touched:Connect( function (hit) |
2 | if hit.Parent:FindFirstChild( "Humanoid" ) then -- make sure its a player that touched it |
3 | local player = game.Players:GetPlayerFromCharacter(hit.Parent) -- get the player in the game |
4 | player.Backpack:ClearAllChildren() -- clear the backpacks children |
5 | end |
6 | end ) |