Can`t optimize my raycast function

I made a similar post a while ago because i couldnt understand
what was causing the lag in my raycast function, but i still havent
found out how to optimize it.
so, basically i want the ray to ignore everything that is not collidable in the workspace,
what i was doing was to get all the descendants that are non collidable in the workspace
and insert them into an ignore list and then cast the ray with that ignore list.
but that causes lag spikes on the game since its getting all the stuff in the workspace
and checking if they are collidable or not.
i want to make a bullet system for my shooter game, but as the ray is also considering non collidable parts, that causes many issues like players using accessories as shields or
bullets randomly hitting invisible parts.
is there any better way i can make this without causing lag spikes?

Instead of getting everything in the workspace and checking if its CanCollide property is true or false use the RaycastResult.Instance. Add the instance to the IgnoreList and then cast the ray again until it hits something that is CanCollide enabled or RaycastResult is nil. To further optimize you could cast the ray from RaycastResult.Position to make the ray shorter each time further optimizing things.

3 Likes