- Home /
Multiple Raycast scripts vs Single Raycast script
Hi c:
I'm making a game where I have multiple objects the player is able to interact with, and I'm wondering what the best solution would be.
Locking the cursor to the center of the screen, and calling an OnMouseOver() method on the interactable objects
Having a script on the player for each different item (Say open door or pickup an item) and casting a Ray from the camera in each script
Having a single Raycast script that changes a boolean on all the interactable objects when looking at them to see if were looking at the object.
The game is intented for PC, so I don't think it should have that big of an impact on performance either way. I was just wondering, since multiple raycasts doesn't seem like a clean method c:
Thank you in advance! :D
Answer by Hellium · Dec 31, 2019 at 09:00 AM
Let's assume that casting multiple rays wasn't an issue regarding the performances. IMHO, it would be a solution hard to maintain. A perfect example would be a pause menu. If we want to disable the interactions, you would need to find and disable all the scripts.
However, having a single script responsible for detecting whether we are approaching an object would be easy to manage (layers, conditions, ....) and disable.
I see two solutions:
Use a custom script, casting a ray each frame, detecting if we are targeting an interactible object (i.e, a gameObject with a specific class implementing an interface / inheriting from a specific class). It will be easy to reference other scripts (player, inventory, ....)
Use the
EventTrigger
with aPhysicsRaycaster
+ scripts inheriting fromOnPointerEnter
/OnPointerExit
. It will be harder to retrieve the reference to the player/inventory/.... from here.
That's true, I didn't think about having to disable all the On$$anonymous$$ouseOver scripts...
I'll go with the single Raycast script, and check if whatever I'm looking at (and is in distance) has implemented an interaface :D
Thanks a lot!