Hello!
I'm implementing a system, where 'interactable' objects highlight if player is looking at them.
I am wondering about the most optimal approach.
First optimisation:
Since this requires for a ray to be cast fairly often to be responsive enough (every frame; or a relatively small time < 0.1s), I am trying to make the result of the raycast reusable
I fire this ray against all geometry and physical objects (let's call them solid from now on) at arbitrary max distance, cache the result and provide it to other scripts
Second optimisation:
I recognise the 'interactable' objects by a 'INTERACTABLE' layer, set within their collider in the Layer Overrides' "Include Layers..."; Generally, the 'interactable' objects can fall within the 'geometry' or 'physical' layer, so I consider it to be a sort of a modifier than a layer used directly on entities. The 'interactable' objects use a Monobehaviour script implementing an 'IInteractable' interface
Since I have the result of the broader raycast I mentioned before, I can check if the hit object's collider has the 'INTERACTABLE' layer present, and if it does, I use TryGetComponent to extract the reference to the script. I then call a 'Highlight' method on it.
So they question is: Is this a sensible approach?
Is it better to perform a broader Physics.Raycast on solid layers and then filter based on other criteria of the hit object (keep in mind that I may reuse the same raycast in other scripts, as getting what the player is looking at is generally useful for many reasons) OR should I instead perform multiple Physics.Raycast, but with more specific layers?
Also, is my current method of using a layer (the 'INTERACTABLE') as basically a tag, if I know all entities within this layer will have a 'IInteractable' script on them prior to getting the component, fine or should I just TryGetComponent every time (I am also checking if the collider hit by Raycast changed since last time, before doing anything again)?