I wanted to make a gun for my game, but for some odd reason when i check If target exists it will crash my game, if i dont check if it exists my game will run fine but of course it will error. I dont really have a clue why this happens, heres my script.
local hitmarker = player.PlayerGui.ScreenGui.HitMarker
if input.UserInputType == Enum.UserInputType.MouseButton1 then
while UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) do
local target = mouse.Target
if target and target.Parent then
if target and Players:GetPlayerFromCharacter(target.Parent) then
sound:Play()
RemoteEvent:FireServer(target.Parent.Humanoid)
coroutine.wrap(createhitmark)(target, hitmarker)
coroutine.wrap(diytroll)()
elseif Players:GetPlayerFromCharacter(target.Parent.Parent) then
sound:Play()
RemoteEvent:FireServer(target.Parent.Parent.Humanoid)
coroutine.wrap(createhitmark)(target, hitmarker)
coroutine.wrap(diytroll)()
elseif Players:GetPlayerFromCharacter(target.Parent.Parent.Parent) then
sound:Play()
RemoteEvent:FireServer(target.Parent.Parent.Parent.Humanoid)
coroutine.wrap(createhitmark)(target, hitmarker)
coroutine.wrap(diytroll)()
end
wait(0.1)
end
end
end
end
Because although you have a wait it’s too little and the while loop with the method will still fire way too fast. Mouse is really fast. Hard to explain but I think you get it. Plus you are doing tons of things like firing remote events, maybe add a bit longer wait.
I’ve figured it out. If there is no target.Parent then the other part of code won’t run and the wait function won’t run too. So you need to do task.wait(.1) after the while … do
local hitmarker = player.PlayerGui.ScreenGui.HitMarker
if input.UserInputType == Enum.UserInputType.MouseButton1 then
while UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) do
task.wait(.1)
local target = mouse.Target
if target and target.Parent then
if target and Players:GetPlayerFromCharacter(target.Parent) then
sound:Play()
RemoteEvent:FireServer(target.Parent.Humanoid)
coroutine.wrap(createhitmark)(target, hitmarker)
coroutine.wrap(diytroll)()
elseif Players:GetPlayerFromCharacter(target.Parent.Parent) then
sound:Play()
RemoteEvent:FireServer(target.Parent.Parent.Humanoid)
coroutine.wrap(createhitmark)(target, hitmarker)
coroutine.wrap(diytroll)()
elseif Players:GetPlayerFromCharacter(target.Parent.Parent.Parent) then
sound:Play()
RemoteEvent:FireServer(target.Parent.Parent.Parent.Humanoid)
coroutine.wrap(createhitmark)(target, hitmarker)
coroutine.wrap(diytroll)()
end
end
end
end
end
Yes, it just freezes when i press down while checking if target is nil. another thing i just found out it only freezes if parent is nil… so im not entirely sure
Oh yeah he’s right, but sitll. I think you need to optimize your code anyway because this would be really laggy for players. Learn about userinputservice.InputBegan and userinputservice.InputEnded to do this stuff that you want.