Reserve RaycastParams, or create a new one for every Raycast?

So lets say I had this RaycastParams, I use it everytime I need to calulate the direction, and object the Player has fired in:

params = RaycastParams.new();
params.FilterType = Enum.RaycastFilterType.Exclude;
params.FilterDescendantsInstances = {char};

Whenever they are used, they go within workspace:Raycast() as an optional method of modifiying the Raycast, and can have some Interesting effects on how they are used, which in this case, will follow the path of where the Player was aiming at the time of execution

result = workspace:Raycast(position, direction, params);

However in most cases I always see them getting discarded, and or removed from code, either by assigning a nil value to a variable, or them getting garbage collected when function had been finished

Couldn’t they be reused for any future raycasting? And if so, what would be a good way of reserving them (if possible)?

Just keep them as a variable? A trivial thing, but things in Lua don’t get deleted/GC’ed if they’re still referred to in some variable or data structure (table).

Better to preserve it. It’s cheaper to reuse RaycastParams when you know the inputs are going to be the same and it also uniquely allows you to modify its members without creating a new object in comparison to most other data types. The same goes with virtually any other data structures that aren’t immutable.

Up to you how to preserve them, it’ll differ on a case-by-case basis. Put them at the top of your script as a constant maybe and just modify FilterDescendantsInstances whenever a new character is added for example.

1 Like

Would this still work if done in a ModuleScript, or maybe other methods such as being moved around in a BindableEvent?

Yes, by virtue of it being a Roblox datatype.

Also:

1 Like

I see, thank you.

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