Raycasts unable to detect newly spawned terrain

Terrain:WriteVoxels() seems to have a duration of time before the terrain fully loads in and is able to be raycasted against. I can’t figure out a reliable way to know how long I need to wait before I can raycast or if I’m going about this in completely the wrong way.

The raycasts are being used to place parts at the surface of the terrain.
No delay:


1 frame delay:

0.1 second delay:

Script that reproduces the issue on a smaller scale

-- Make sure we don't detect terrain from any previous tests
workspace.Terrain:Clear()
task.wait(0.1)

-- Write a 4x4x4 stud cube centered at 2,2,2
workspace.Terrain:WriteVoxels(
    Region3.new(Vector3.zero, Vector3.one*4),
    4,
    {{{Enum.Material.Grass}}},
    {{{1}}}
)

-- Uncomment this and the raycast won't detect the terrain
-- task.wait()

-- Raycast down from right above the terrain voxel
local hit = workspace:Raycast(Vector3.new(2, 5, 2), -Vector3.yAxis*2)
print(if hit then `Hit {hit.Instance}` else "No hit")

Output with task.wait() left commented out: No hit
Output with task.wait() uncommented: Hit Terrain

1 Like

I’m not entirely sure when the collision update happens for terrain if it isn’t immediate. You can try replacing the task.wait with all the RunService waits & see after which one it starts working. My best guess would be RunService.PostSimulation.

Based on the code sample tho, seems like you need to wait at most one frame.