Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I keep my gun shooting without a target?

Asked by 2 years ago

I am using a hit detection system with guns by using what the cursor is hovering over as the target. to put it simply, if the cursor is on someone while shooting, that person takes damage.

My issue is that when I shoot the sky my gun will stop firing and throw an error saying I am trying to index the sky's parent which is nil. How can I get around this so that my gun will shoot no matter what I am aimed at?

-- click to attack --
wait()
script.Parent.Activated:Connect(function()

    local shooting = true
    while shooting == true do
    if Ammo > 0 and not Reloading then
        Ammo -= 1
        print(Ammo)
        script.Parent.GunShot:Play()
        TextLabel.Text = Ammo.."/"..MaxAmmo

        workspace.Camera.CFrame = workspace.Camera.CFrame * CFrame.Angles(0.03,-0.008,0)
        wait()
        workspace.Camera.CFrame = workspace.Camera.CFrame * CFrame.Angles(-0.01,0.0065,0)
        wait()

            if Mouse.Target.Parent:FindFirstChild("Humanoid") then
                script.Parent.DealDamage:FireServer(Mouse.Target.Parent, 15)
            end

            if Ammo == 0 then
                Reload()
            end

    elseif Reloading == true then
        Reload()
        script.Parent.GunShot:Stop()
    end 

    Mouse.Button1Up:Connect(function()
        shooting = false
    end)
        wait(.03)
    end
end)

1 answer

Log in to vote
1
Answered by 2 years ago
-- click to attack --
wait()
script.Parent.Activated:Connect(function()

    local shooting = true
    while shooting == true do
    if Ammo > 0 and not Reloading then
        Ammo -= 1
        print(Ammo)
        script.Parent.GunShot:Play()
        TextLabel.Text = Ammo.."/"..MaxAmmo

        workspace.Camera.CFrame = workspace.Camera.CFrame * CFrame.Angles(0.03,-0.008,0)
        wait()
        workspace.Camera.CFrame = workspace.Camera.CFrame * CFrame.Angles(-0.01,0.0065,0)
        wait()
        if Mouse.Target ~= nil then -- check if the value of Target is nil so it wont error
            if Mouse.Target.Parent:FindFirstChild("Humanoid") then
                script.Parent.DealDamage:FireServer(Mouse.Target.Parent, 15)
            end
        end
            if Ammo == 0 then
                Reload()
            end

    elseif Reloading == true then
        Reload()
        script.Parent.GunShot:Stop()
    end 

    Mouse.Button1Up:Connect(function()
        shooting = false
    end)
        wait(.03)
    end
end)
0
Ah, I knew I couldn't not have that error I just wasn't sure how to handle the error with the code. This worked for me, thank you! DaGlizzzzzzyyyy 34 — 2y
Ad

Answer this question