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

Attempt to index target with nil?

I am making damage dealt by guns rely on the position of the cursor on the screen, however when I shoot the npc or dummy bot I have put in to test, the console returns an error saying "attempt to index nil with 'Target' ". I'm slowly learning Lua but it can be challenging, any help would be highly appreciated!

There is more to the script but for simplicity I have included only the part with the issue. (Line 25 here)

-- global reload function --
local function Reload()
	Reloading = true
	wait(1)
	Ammo = MaxAmmo
	Reloading = false
end


-- holding item, connect --
script.Parent.Equipped:Connect(function()
	print("Pistol equipped")
end)


-- click to attack --
script.Parent.Activated:Connect(function(Mouse)
	
	print("fired "..Ammo)
	if Ammo > 0 and not Reloading then
		Ammo -= 1
		print(Ammo)
		script.Parent.GunShot:Play()
		--recoils--
		if Mouse.Target.Parent:FindFirstChild("Humanoid") then
			script.Parent.DealDamage:FireServer(Mouse.Target.Parent, 20)
		end

6 comments

0

Just to clarify here, is the script a serverscript (not a localscript), or a localscript?

0

Alright, I've read your code further, and have concluded that this is a localscript.

0

Use player:GetMouse() instead of the first argument the activated function returns

0

How is it a localscript? You are gonna let yourself hear the gun sounds?? (not offending anyone here but pretty sure its a script (except the localscript is being weird lol))

0

it is a local script I never even thought of the rest of the server hearing the gun sound lol. I'll change some stuff up and probably be back tomorrow with more questions.

0

ooh ok that make sense

1 answer

✓ Accepted answer

Tool.Activated does not have any parameter, which means the mouse argument is defaulted as nil, therefore there is no Target on nil values. You should make player:GetMouse() to get the mouse and it will work.

3 comments

0

by the way use LocalScript for that, you can't do if its in a Script

0

That did it, thank ya sir. The other comments did make a good point about the sound not playing for the server though. Credit to all, don't have enough karma to upvote tho.

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