I have a script that gives players ammo when it’s parent which is a part is touched. But I keep getting this error message saying (ScriptName):Attempt to index nil with ‘FindFirstChild’ Is there a fix for this?
It is in this line:
local ammolimit = tool:FindFirstChild("AmmoLimit")
local part = script.Parent
local pickupSound = part:WaitForChild("Pickup")
local pickup = false
part.Touched:Connect(function(otherPart)
local humanoid = otherPart.Parent:FindFirstChild("Humanoid")
local tool = otherPart.Parent:FindFirstChildWhichIsA("Tool")
local ammolimit = tool:FindFirstChild("AmmoLimit")
local ammo = tool:FindFirstChild("Ammo")
local maxammo = tool:FindFirstChild("MaxAmmo")
local ammoplus = tool:FindFirstChild("AmmoPlus")
if humanoid and maxammo.Value < ammolimit.Value and pickup == false then
pickup = true
pickupSound:Play()
part.Transparency = 1
maxammo.Value = maxammo.Value + ammoplus.Value
pickup = false
wait(0.509)
pickupSound:Stop()
pickupSound:Destroy()
part.Parent:Destroy()
end
end)
Sometimes tool is invalid, you can use return to stop the script from following when tool is invalid or for other reasons.
local part = script.Parent
local pickupSound = part:WaitForChild("Pickup")
local pickup = false
part.Touched:Connect(function(otherPart)
local humanoid = otherPart.Parent:FindFirstChild("Humanoid")
local tool = otherPart.Parent:FindFirstChildWhichIsA("Tool")
if not humanoid or not tool then return end
local ammo = tool:FindFirstChild("Ammo")
local ammolimit = tool:FindFirstChild("AmmoLimit")
local maxammo = tool:FindFirstChild("MaxAmmo")
if not ammolimit or not maxammo then return end
local ammoplus = tool:FindFirstChild("AmmoPlus")
if maxammo.Value < ammolimit.Value and pickup == false then
pickup = true
pickupSound:Play()
part.Transparency = 1
maxammo.Value = maxammo.Value + ammoplus.Value
pickup = false
wait(0.509)
pickupSound:Stop()
pickupSound:Destroy()
part.Parent:Destroy()
end
end)