I’m making a script for the gun but the script is not working.
Error in console: Attempt to index nil with ‘HumanoidRootPart’
local player = game.Players.LocalPlayer
local CharacterPlayer = player.Character
local Mouse = player:GetMouse()
local Ammo = 5
local AmmoLeft = 5
local MaxDistance = 100
local Equipped = false
local Reloading = false
script.Parent.Equipped:Connect(function()
Equipped = true
game.ReplicatedStorage.Ammo:Fire(player, Ammo)
end)
script.Parent.Unequipped:Connect(function()
game.ReplicatedStorage.AmmoUnequipped:Fire(player)
Equipped = false
end)
Mouse.Button1Down:Connect(function()
if Mouse.Target.Parent:FindFirstChild("Humanoid") and AmmoLeft >= 1 and not Reloading and
Equipped then
local Character = Mouse.Target.Parent
local Humanoid = Character:FindFirstChild("Humanoid")
script.Parent.Handle.FireSound:Play()
AmmoLeft = AmmoLeft -1
game.ReplicatedStorage.LessAmmo:Fire(player)
AmmoLeft = AmmoLeft -1
if (CharacterPlayer.HumanoidRootPart.Position - Character.HumanoidRootPart.Position).Magnitude
<= MaxDistance then
script.Parent.TakeDamageEvent:FireServer(Character)
elseif not Mouse.Target.Parent:FindFirstChild("Humanoid") and AmmoLeft >= 1 and not Reloading
and Equipped then
script.Parent.Handle.FireSound:Play()
AmmoLeft = AmmoLeft -1
game.ReplicatedStorage.LessAmmo:Fire(player)
elseif AmmoLeft == 0 and not Reloading and Equipped then
Reloading = true
game.ReplicatedStorage.Reload:Fire(player)
script.Parent.Handle.Reload:Play()
wait(3)
AmmoLeft = 5
Reloading = false
end
end
end)
Okay, this error is something you are going to see a lot now, its something I ABSOLUTELY hate. Instead of using FindFirstChild use WaitForChild and if that doesn’t work, t-t-try resorting to a… wait() oh the agony of using a wait(). Anyways yes that should work using WaitForChild() or a wait().
See, roblox studio is weird when it comes to this, I had an error exactly like this and there was a player variable before leaderstats but when I tried referring to leaderstats it didn’t work so I resorted to WaitForChild.
It’s just a suggestion, because this exact same thing happened to me, and it was weird, but it worked when I used WaitForChild, I have a whole topic on it, but let’s not continue this anymore.
Would it change anything if you were to add a local Target variable?
Mouse.Button1Down:Connect(function()
local Target = Mouse.Target
if Mouse.Target.Parent:FindFirstChild("Humanoid") and AmmoLeft >= 1 and not Reloading and Equipped then