How do I check if RaycastResult.Instance exists if the code always return an error when .Instance is indexed?

  1. What do you want to achieve? I want to check if RaycastResult.Instance exists, if not perform this code, else that code.

  2. What is the issue?

if raycastResult.Instance ~= nil then
	if players:GetPlayerFromCharacter(raycastResult.Instance.Parent) then
		return true
	end
	return false
end
return false

The error is on the first line: attempt to index nil with ‘Instance’


Since this post has a solution already, I'll still left the code down here incase someone get the same problem, the fixed code is down there:
if raycastResult ~= nil then
	if players:GetPlayerFromCharacter(raycastResult.Instance.Parent) then
		return true
	end
	return false
end
return false
  1. What solutions have you tried so far?
    I did look for solutions in developerHub but that didn’t help. I also tried using metatable with metamethod of __index but unfortunately RaycastResult itself isn’t a table.

    I also tried different variations of that if statement, but it didn’t help.

In Conclusion, I want to ask if there’s any possible way to check if RaycastResult.Instance exists, if there’s none, is there a way to check using other functions?

WorldRoot:Raycast returns nil if the raycast didn’t hit anything. The Instance field is never nil. So check if raycastResult ~= nil instead.

2 Likes

Thanks, I checked the RaycastResult, I’ll update the code

My ray is not nil and then it becomes nil on the next line? (Breakpoints)

That is a separate bug related to Luau. This is probably a result of the Garbage Collector collecting the result when it shouldn’t be.