Whats wrong with my code that gives sword then block is touched

script is local and located in StarterPack sword is located in ReplicatedStorage idk what wrong

local part = game.Workspace.P5.Cloud1
local plr = game.Players.LocalPlayer
local Replicated = game:GetService("ReplicatedStorage")
local startP = game:GetService("StarterPack")
local db = false

part.Touched:Connect(function(other)
	if db == true then return end
	if part.ClassName == "Part" then
		db = true
		local success, sword = pcall(function()
			local sword = Replicated.SwordOfLight:Clone()
			return sword
		end)
		if success and sword then
			sword.Parent = script.Parent
			print("Sword added to backpack")
		else
			print("Error adding sword: ")
		end
	end
end)

its adding sword but sword dont work

You should not be attempting to give a player a tool on the client side.
Also, you should be checking whether or not the part that has touched your giver is a descendant of a player’s character.
Here’s an example of what I might do:

local Players = game:GetService("Players")
local swordGiverPart = game.Workspace:WaitForChild("SwordGiver")
local swordTool = game.ServerStorage:WaitForChild("Sword") -- change this to reference the sword.

swordGiverPart.Touched:Connect(function(hitPart)
    if hitPart.Parent:FindFirstChild("Humanoid") then
        local player = Players:GetPlayerFromCharacter(hitPart.Parent)
        if not player then return end
        local swordClone = swordTool:Clone()
        swordClone.Parent = player.Backpack
    end
end)

I’d do something like that ^

TL;DR
Don’t attempt to give players tools on the client side. Only do it on the server side.

3 Likes

ye thank you but its still that problem where you put your script and what type of script this is? maybe then i set sword to StarterPack its working but if i step on part its appear in my inventory but its not working

You would use a server side script and place the logic there. In this case, you would put the script in ServerScriptService or another container that accepts scripts.

if i put this script in ServerScriptService its dont work but if put in StarterPack, StarterPlayerScripts, StarterCharacterScripts its works(because its local script)