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

I'm trying to make a brick that gives a sword on touch. What's wrong with my script?

Asked by 6 years ago

The sword ("Basic Sword") that I'm trying to use here is placed under game.Lightning, can someone tell me what's wrong with this script?

local x = game.Players.LocalPlayer.Backpack
local y = game.Lighting["Basic Sword"]
script.Parent.Touched:Connect(function(
 y:Clone().Parent = x
end)

Thanks!

1 answer

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

First, you have a syntax error, since you aren't closing the ( in your anonymous function that handles the Touched event.

Also, you're going to have issues with this script when you test on a real Roblox server since game.Players.LocalPlayer is not accessible in server Scripts, only on the client. You will have to get a reference to the character who touched the brick in a different way. We can do this by using the argument passed to handlers for the Touched event, which is the other part that touched the part you're listening for the event on. We can check to see if this part belongs to a player by using game.Players:GetPlayerFromCharacter().

Also, it's best practice to use ServerStorage instead of the Lighting for Parts, Models , etc. that you want to keep "hidden" but accessible.

Lastly, you will want to make sure you only add the sword to the player's backpack once. Since Touched events often fire multiple times very rapidly, you could end up with multiple swords in your backpack even if you only meant to touch the giver part once. We will do this check by seeing if an item called "Basic Sword" already exists in the player's backpack.

So, once you've moved the sword into ServerStorage, change the script to the following, which takes all of the above into account:

local sword = game.ServerStorage["Basic Sword"]

script.Parent.Touched:Connect(function(otherPart)
    local player = game.Players:GetPlayerFromCharacter(otherPart.Parent)
    if player then
        local backpack = player.Backpack
        local playerAlreadyHasItem = backpack:FindFirstChild("Basic Sword")
        if not playerAlreadyHasItem then
            sword:Clone().Parent = backpack
        end
    end
end)
0
Thanks, dude! That's appreciated :) SirLuisFonsi 9 — 6y
Ad

Answer this question