Avoiding errors in conditionals?

Hey there! So, i made a script where it constantly raycasts to the player’s humanoid root part checking if it has something.

If it doesn’t, we destroy it.

Now, i did this to check if it doesn’t have it;
1 - Raycast
2 - do if not to check if it doesn’t have it

Now here comes the problem, when the part doesn’t have it, it prints an error.

It still works i guess but i dont want to be spammed by useless errors since it does work.
The code inside the if statement works, it just prints an error everytime. How do i fix this?

Also, i could just make an else statement but the script doesn’t allow me so, i’d have to rewrite the script. Maybe my last resort

Thanks!

1 Like
local result = workspace:RayCast(info)
-- to prevent the error you need to do this, 
if result then 
   -- code --
end
2 Likes

I was gonna say something, but @BANSA168 beat me to it.

But anyways yeah, just put that in an if-statement. If the ray doesn’t hit anything, it will return nil which most likely is what is causing the error.

1 Like

But i want to detect if it doesn’t hit anything, so i could delete it.

1 Like
if not result then
   -- code
end
2 Likes

What about detecting something inside it? Like

If not a:FindFirstChild ("e") then

I tried doing that, it returned the error so i came here.

Raycasting is for 3D space and :FindFirstChild is just in what folder something is located, 2 completely different things. There could be a few reasons why it errored, either “a” is nil or it doesn’t have a :FindFirstChild method

1 Like

I think i did .instance:FindFirstChild or smth, it did work when i didn’t put a “not”

It says the “e” is nil when i put a “not”
(Which idk why it still prints an error, ITS AN IF STATEMENT, tho theres prob a reason idk)

If you want to check if there’s something inside raycast’s result instance then you should use the code I sent you and then put your :FindFirstChild code

1 Like

I want to do the opposite of it tho, checking if its NOT in the part

local result = workspace:RayCast(info)
if result then 
   if not result.Instance:FindFirstChild('e') then
      -- code that you wanna run after --
    end
end
1 Like

I just realized i could do “else” on that if statement

Also, i tried this and didnt work cause its checking if the part is valid and for my case, it always is.