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

Why doesn't this script work?

Asked by 8 years ago

So, I made a script that SHOULD remove weapons (in this case, the "ClassicSword") when touched a brick called "RedInteractive". For some reason - it doesn't work. Output is not giving any errors, but it doesn't print out what I've told it to print. Can anyone help? Big thanks!

Sincerely, Director1406.

P.S. Code is bellow

p = game.Players.LocalPlayer


game.Workspace.RedInteractive.Touched:connect(function(hit)
    if p.Backpack:FindFirstChild("ClassicSword") == true then
        print("entering castle, removing weaps")
        p.Backpack.ClassicSword:Destroy()
    elseif p.Backpack:FindFirstChild("ClassicSword") == false then
        print("leaving castle, giving back weaps")
        local copy = game.Lighting.ClassicSword:Clone()
        copy.Parent = p.Backpack
    end
end)
0
is this in a LocalScript (as you're using LocalPlayer)? LightningRoMan 100 — 8y
0
Yes it is. Director1406 5 — 8y

1 answer

Log in to vote
0
Answered by 8 years ago

If you're using a local script, DON'T. You don't need to use a local script for this process. The main reason your code is not working is because you use game.Players.LocalPlayer in order to get the player. The problem with this is that the script is probably in Workspacemeaning there is no local player. Meaning p = nil. The way you can fix this is by getting the player from the part that touched the brick. In this case, "hit". The code would look something like this,

-- IN REGULAR SCRIPT
-- remove local player
game.Workspace.RedInteractive.Touched:connect(function(hit)-- I would recomend that you put this inside of the part and use script.Parent.Touched instead because that would work much better

    if not hit.Parent:FindFirstChild("Humanoid") then return end-- if hit isn't part of a character returns end

    local p = game.Players:GetPlayerFromCharacter(hit.Parent)--Gets the player from the character.

    if p.Backpack:FindFirstChild("ClassicSword") == true then
        print("entering castle, removing weaps")
        p.Backpack.ClassicSword:Destroy()

    elseif p.Backpack:FindFirstChild("ClassicSword") == false then
        print("leaving castle, giving back weaps")
        local copy = game.Lighting.ClassicSword:Clone()-- I would also recomend using ServerStorage instead of Lighting

        copy.Parent = p.Backpack
    end
end)

That should work. Good luck!

Ad

Answer this question