So I want to make it when a player passes through a part(it’ll have CanCollide off and transparency to 1), they will get a sword. How can I give it to them and then take it away when they go through the part again?
2 Likes
Use the Touched event.
script.Parent.Touched:Connect(function(part)
--Find character
local character = part:FindFirstAncestorOfClass("Model")
if(character) then
--Find humanoid
local humanoid = character:FindFirstChild("Humanoid")
if(humanoid) then
--See if player already has tool
if(not player.Backpack:FindFirstChild(tool.Name) and not character:FindFirstChild(tool.Name)) then
--Give tool to player
else
--Remove tool from player
end
end
end
end)
Edit: it’s also a good idea to use a cooldown/debounce so the script doesn’t continually give and take away the tool to players.
1 Like
Place your sword in ReplicatedStorage, and insert a (server) Script inside the part that you want players to touch to get their sword.
Then in the script, you can call the Touched event, which detects when that specific part touches something. And to check that a player has touched the part, make an if statement to check whether or not the thing that touched the part has a humanoid. And then we give the sword.
Here is your code:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local Sword = ReplicatedStorage:WaitForChild("Sword") -- put the name of the sword here
local Part = script.Parent
Part.Touched:Connect(function(hit) -- 'hit' is what touched the Part
if hit.Parent:FindFirstChildWhichIsA("Humanoid") then -- if humanoid exists
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
if player.Backpack:FindFirstChild("Sword") or player.Character:FindFirstChild("Sword") then -- if sword exists in the backpack or is already equipped
player.Character:WaitForChild("Humanoid"):UnequipTools() -- unequips any tool
player.Backpack:FindFirstChild("Sword"):Destroy() -- removes the sword
else -- if sword is not in the backpack or if the sword isnt equipped
Sword:Clone().Parent = player.Backpack -- clones and places the sword in the backpack
end
end
end
end)
9 Likes