The script works perfectly fine, it only gives me one sword and wont give me another if I have one.
BUT
there are these errors and they’re annoying so how would I get rid of them?
i tried local Backpack = player:FindFirstChild("Backpack")
and local Backpack = player:WaitForChild("Backpack")
but they both give me the error
Workspace.Touch Tool Giver.Main:4: attempt to index nil with ‘FindFirstChild’
Workspace.Touch Tool Giver.Main:4: attempt to index nil with ‘WaitForChild’
Here is the script
script.Parent.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
local Backpack = player:FindFirstChild("Backpack")
local FindTool = Backpack:FindFirstChild("Sword")
if FindTool then
print("has tool")
else
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
local tool = game.ReplicatedStorage.Sword:Clone()
tool.Parent = plr.Backpack
wait()
end
end)
You need to check if player is nil. Think about how the code flows. What happens if hit.Parent isn’t a player character? Then according to the documentation, GetPlayerFromCharacter returns nil. Attempt to index X with Y means that you tried to do X.Y, X[Y], or X:Y and X is incompatible. In this case, X is nil.
So player:FindFirstChild(“Backpack”) means you are attempting to index player (x) with FindFirstChild (y). Player (x) is nil.
This would give you a similar error, just for the sake of learning.
local x = function() print("TestFunction") end
x() --> TestFunction
print(x.SomeValue) --> Error: Attempt to index function with SomeValue
Several ways, but I think this way is pretty succinct.
local player = game.Players:GetPlayerFromCharacter(hit.Parent) -- same as your code
if not player then return end -- ends the function if player is false or nil
The other way is like what you’ve already got on this line
You would just do that with player instead of FindTool.