Raycast errors and says "attempt to index nil with 'Instance'" in raycast module

Hello, I want to make a raycast module. However, it errors and says “attempt to index nil with ‘Instance’” when i try to make a check to see if the ray has an instance it intersected with. I tried to make it check to see if the result exists but it doesn’t execute anything.

This is part of the code.

local result = workspace:Raycast(origin, direction, params)
	
	if result.Instance then
		onRayHit(result, setting, player, gun)

		return
	end
2 Likes

Change it to

if result and result.Instance then
2 Likes

The result isn’t always guaranteed, say your raycast goes 10 studs in front of you. If there is nothing within 10 studs in front of you, it returns nil. The solution is to add a simple check whether the result is nil or not before doing the if result.Instance then line.

2 Likes

I forgot to multiply the direction value with a number for range, my bad. It couldn’t reach anything because it was too short. Also, I don’t need a check for checking if the result has intersected with an instance apparently. Thank you all for trying to help me though.

1 Like

It is still best practice to check for a result first before indexing the hit Instance.
The reason your problem solved itself was because your Raycast is simply hitting something after you properly set its distance. If you can’t guarantee that your Raycast hits something you should check for a result before indexing.

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