today i started work on a new project, and the tool i was creating needed a raycast. i hadn't used them in a while, so i checked the API, only to see that the ray.new method i used last was tucked away - while the search function instead showed the :Raycast method.
the page all but seemed to say outright that ray.new was deprecated, and :Raycast seemed easier, so i decided to give it a shot.
except that it bricked everything. as i understand it, you fire it with the parameters and it simply returns an object that has parameters you can read individually for the results, but when i use :Raycast it doesn't seem to return anything at all.
heres the code:
--some other irrelevant variables if tool.Equipped then uis.InputBegan:Connect(function(input, gameProcessed) if gameProcessed then return end if input.UserInputType == Enum.UserInputType.MouseButton1 then local mouselocation = uis:GetMouseLocation() local newpart = Instance.new("Part") newpart.Parent = game.Workspace.PlayerBuildingStuff local castres = workspace:Raycast(camera.CFrame.Position, camera.CFrame.LookVector) print (castres) local partcframe = CFrame.new(castres.Position) print (partcframe) newpart.CFrame = partcframe end end) end
sorry for the abominable code, i just slapped it together and hit a total wall with this raycast business.
the print (castres) returns nul, and the first call for any value of castres bricks the function with an "attempt to index nil" error.
i really dont know whats wrong. its probably something simple, but if anyone has any advice id really appreciate it. code optimization recommendations included :)
The raycast result, in case your "castres", is not the instance nor the position hitted by the ray, its a table with these values inside:
RaycastResult.Instance: The BasePart or Terrain cell that the ray intersected. (nil if there is none)
RaycastResult.Position: The world space point at which the intersection occurred, usually a point directly on the surface of the instance.
RaycastResult.Material: The Material at the intersection point. For normal parts this is the BasePart.Material; for Terrain this can vary depending on terrain data.
RaycastResult.Normal: The normal vector of the intersected face.