Detect and run code if mouse.hit.position is nil

Basically i need to run code if CFrame.new(mouse.Hit.Position) is nil in separate if function to not let errors and bugs break gameplay.
Heres some barebones script you can use to understand what i mean:
local dir = CFrame.new(mouse.Hit.Position)
if [idk what to put there to run if "dir" is nil] then
[code]
else
[code if its not nil]
end

1 Like

I don’t think that mouse.Hit or mouse.Hit.Position can be nil, but if you want you can either wrap it in a pcall like

pcall(function()
 local dir = CFrame.new(mouse.Hit.Position)
 --code if its not nil
end)

or do

local hit = mouse.Hit
if hit then
 local dir = CFrame.new(mouse.Hit.Position)
 --code if its not nil
end

изображение
it can be nil if position is nil

1 Like

simply make:

if mouse.Hit then
--code

end

To check if a value is nil you can simply compare to it!

local dir = CFrame.new(mouse.hit.Position)
if dir == nil then
    -- dir is nil
else
    -- dir was not nil
end

Hope this helps!

You can just do

if mouse.Hit == nil then
blah blah blah
end

Worked for me when I was working on a game

1 Like

Did not work, "Attempt to index nil with ‘Position’ "

Did not work too, "Attempt to index nil with ‘Position’ "

Same there as ones above, "Attempt to index nil with ‘Position’ "

Nobody yet told me working line of code that will let me run function if mouse.Hit.Position is nil

nvm realised other part of script did errors

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