Hello. Recently I’ve created a lot of great behaviours using small modular components and projectiles. I’m wondering now how I can go about achieving similar things using raycast. With my projectiles I will have, for example, a Shoot() method which simply spawns a projectile prefab. The projectile will contain various scripts that manipulate the projectile and control what happens when it hits something. I’m struggling to think of how to achieve this with raycasts as every behaviour component will essentially need to know about the Ray that is “shot” and therefore break the modularity. I’m hoping someone might shed some light on how to approach this. Thanks for reading.
Standard practice for projectiles in Unity typically uses one of these three models:
- The projectile model, where you have an object with a collider and a rigidbody, with a velocity. In this model we rely on Unity’s collision detection to tell us when the projectile hits something, and respond to it in OnCollisionEnter or OnTriggerEnter functions.
- The raycast model. In this case we pretend that the projectile is moving so fast that it will essentially always hit its target within one frame. This is used in the case of modelling real-life guns and laser beams etc… In this model you do a raycast and just hit whatever the raycast hits.
- The hybrid model - Sometimes you want to model your projectile as an actual moving projectile, but it moves too fast and is too small for Unity’s collision detection to work reliably. In this case you do raycasts every physics frame in the direction the projectile is moving to try to pre-emptively detect any collisions that will happen, while also using OnCollisionEnter, etc…
In all of these cases, the Raycast call or the OnCollisionEnter function will give you a reference to the object you hit. It’s up to you then whether or how you communicate information to scripts attached to that collider. Only tjhe script that is performing the raycast needs to know about the raycast itself. But you might want to have a method on the receiving script like “GetShot()” which handles what happens when that component gets hit by the projectile. You can use this same method whether you’re using raycasts or collision detection.