Need help with spawning a model to the mouse position

I’m making a spell system. And there’s a script where I need to summon a spike where the mouse is.

Some things to know:

  • This is a ModuleScript inside a Script,
  • The player can be in first person or 3rd person at will,
  • I have set the PrimaryPart to the spike,
  • I use plr:GetMouse and mouse.Hit.Position,
  • plr is got with the RemoteEvent from the second LocalScript
  • The error message is “attempt to index nil with ‘Hit’”

Here’s the ModuleScript for executing the spell,

	elseif act == "P1" then
		local mouse = plr:GetMouse()
		local target = mouse.Hit.Position
		local sp = ReplicatedStorage:WaitForChild("Spayk"):Clone()
		sp.Parent = workspace
		sp:MoveTo(target)

		local alreadyHit = {}
		local destroyScheduled = false
		local function damg(hit)
			local parent = hit.Parent
			if not parent and alreadyHit[parent] then return end
			alreadyHit[parent] = true
			local humanoid = parent:FindFirstChild("Humanoid")
			local targetplayer = Players:GetPlayerFromCharacter(parent)
			if humanoid then
				if isPlayerCharacter(parent) then
					if canDamage(plr, targetplayer) then
						humanoid:TakeDamage(60)
						playHitExclamationSound(hit)
					end
				else
					humanoid:TakeDamage(55)
					playHitExclamationSound(hit)
				end
				if not destroyScheduled then
					destroyScheduled = true
					task.wait(5)
					safeDestroy(sp)
				end
			end
			sp.Hurt.Touched:Connect(damg)
			task.wait(5)
			safeDestroy(sp)
		end

Here’s the LocalScript for firing the spell,

		if i.KeyCode == spell1key then
			if db1 == false then
				db1 = true
				rep:FireServer("P1")
				task.wait(20)
				db1 = false
			end
		end
1 Like

the error happens because hit in the damg function is nil

there’s probably more to debug but you can do a simple fix with

if not hit then return end
1 Like

The mouse.Hit is not working though…

plr:GetMouse() only works in a LocalScript. Your ModuleScript runs on the server, so plr:GetMouse() returns nil, causing the Hit error.

1 Like

That worked. I did what the solution was in this

Easy mistake I did the same thing when working with tank guns.. Why I seen it right away.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.