Value of type 'Instance?' could be nil

Hello, it is me again. I am writing a gun script for my friend’s group, and I ran across a peculiar error I don’t seem to understand. So I am using strict typing in my Luau, and I set a specific type of ‘Instance’ to a variable I expect to contain an Instance. This is Via the RayCastResult.Instance for my raycasting (obviously, duh!)

Anyays here is a snippet of my code.

-- UIS is defined as the UserInputService via game:GetService()

UIS.InputBegan:Connect(function(capturedInput, isGameProcessedEvent)
	
	if capturedInput.UserInputType == Enum.UserInputType.MouseButton1 and canShoot then
		local mouseTarget = mouse.Target
		local mouseHitP = mouse.Hit.p
		local muzzle = gunParts:FindFirstChild("Muzzle") -- A part inside the gun in which I am shooting the ray from
		
		if muzzle then
			local rayCastParams = RaycastParams.new()
			rayCastParams.FilterDescendantsInstances = {gun.Parent, gun}
			rayCastParams.FilterType = Enum.RaycastFilterType.Blacklist
			local rayCastResult = workspace:Raycast(muzzle.Position, mouseHitP, rayCastParams)
			if rayCastResult and rayCastResult.Instance then
				local hitPart:Instance = rayCastResult.Instance
				
				if hitPart then
					if hitPart:IsA("BasePart") then
						if hitPart.Parent.Name == "Vest" then
							
						end
					end
				end
			end
		end
	end
	
end)

The error (more like warning) looks like this.

image

What have I tried to solve this you ask? Well it’s warning me that the instance could be nil, so I tried allowing my variable to accept a nil value by adding ? to the end, however that didn’t fix it. So I added that if statement that checks if the hitpart exists and isn’t nil, but that still didn’t fix it. I don’t understand what is happening. Please help as soon as possible!

It’s warning you that a hard reference of [instance].Parent may lead you to a non-instance value, like nil if it doesn’t exist. It’s basically asking you to do a safer reference like hitPart:FindFirstAncestor("Vest") instead, which would allow you to handle the event that its parent doesn’t exist.

1 Like