Index nil with position

Hey there!

I am currently making a game and i need a gun system, so i had a go at making one whilst using a YouTube tutorial as support. I followed every step and got an error that i have tried fixing but it just wont work.

The error:

attempt to index nil with ‘Position’

The Script:

-- This is a server script within a tool that is inside of workspace. This is just a small fraction of the script.

local function shootfunction(plr, hit, target)
	if reloading then return end
	if ammo.Value < 1  then
		reload()
		return
	end
	
	local ray = Ray.new(gun.SmokePart.Position, (hit.Position - gun.SmokePart.Position).unit * 100) -- Error occuring here (hit.Position doesnt work)
	local part, pos, globalVec = game.Workspace:FindPartOnRay(ray, gun.Parent, false, true)
	if part then
		if part.Parent:FindFirstChild("Humanoid") then part.Parent.Humanoid:TakeDamage(15) end
	end

Thank you! :smile:

what line of the code does the error appear

It is occurring here:

local ray = Ray.new(gun.SmokePart.Position, (hit.Position - gun.SmokePart.Position).unit * 100) -- Error occuring here (hit.Position doesnt work)```

Hit is a position it is not an instance, right? I think it should be just hit.

Could you provide a little more info (console error would be useful).

I tried removing .Position and now i’ve got this error:

attempt to perform arithmetic (sub) on nil and Vector3

Line:

local ray = Ray.new(gun.SmokePart.Position, (hit - gun.SmokePart.Position).unit * 100)

Did you mean this?

This would indicate that hit isn’t even being assigned a value. When calling the function named “shootfunction” are you passing a 2nd value as an argument to the function (which would satisfy the 2nd parameter “hit”)?

Im pretty sure the hit value was assigned when creating the ray cast, but i may be wrong. If it helps i can provide the entire script and youtube tutorial if needed.

There are values when firing the server:

Fire:FireServer(mouse.Hit, mouse.Target)

But im not sure if those would carry over to the server.

Well the console error is stating that you’re attempting to access a field named “Position” of a nil value.

You could debug by adding print(hit, target) that the values are correctly received by the server within the first line of the function connected to the corresponding OnServerEvent event.

1 Like

I have fixed the problem.

It turns out that when i was connecting the function i accidently added brackets.