- Home /
Ray Casting - Trigger function
Hey guys, simple question about ray casting:
Does Unity provides a function similar to OnTriggerEnter()
that is automatically fired every time an object was hit by a Raycast?
Let me clarify the problem:
I have two scripts. The first one is attached to the PlayerController camera (which fires a Raycast on the Update method), the second one called KeyObjectController is attached to every GameObject in the scene that is marked as a key object. Now, from this script, I'd like to create a Lerp animation on the material to create a sort of highlight effect, only when the object is hit by the player camera Raycast. I know I could check the hit game object tag directly form the player script, and call the sendMessage
method to invoke the Highlight function, but I'd like to keep the logic directly into the KeyObjectController script.
Is that possible?
Thank you guys.
Answer by robertbu · May 18, 2014 at 02:16 PM
Unity does not provide this functionality. You are going to somehow communicate to the object from the Raycast() code. As an alternate, you can create a public function and call it directly. So say in your KeyObjectController script you had a RaycastHitMe() function. From the raycast code you could do:
var key = hit.collider.GetComponent(KeyObjectController);
if (key != null)
key.RaycastHitMe();
If you are using C#, another possibility is to use Events and Delegates and have all of your KyeOjbectController scripts listen for a Raycast hit event, and then check the transform hit against its own transform.
It's a pity Unity lack of this feature, but your solution works great so it's not a big deal. Since we don't also have the counterpart "onRayCastExit" function, I have to save a reference to the lastest game object that was hit by RayCast, and call the "key.RayCastExit()" function when a new object was hit. Again, thanks for your help Robert.