Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I keep my gun shooting without a target?

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

-- 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)

1 comment

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.