Unity3D: colliders are your friends
Here’s another portion of Unity3D beginner tips and tricks, and today it’s about using physics engine for something more than just making things go bump. (Pic related.)
Did you know, that every collider you click/tap sends an event to all the scripts attached to the same
gameObject? Now you do. Implement
void OnMouseDown() method in any of those scripts to get the message. Make sure your object is not in Ignore Raycast layer though, ’cause raycasting is what making these messages possible. A pretty useful mechanic for implementing UIs (since you can attach colliders to virtually anything) or otherwise interacting with objects in the scene.
Next one is more complex. Let’s say you got objects that need logical connection to each other. See Railyard, trains are being made of cars of the same type. First solution that comes into mind is just store references to cars in arrays and do a bunch of array processing each frame. (That actually works, and I did implement that in the early prototype.) But making your hardware do extra work is unnecessary, especially when you have access to a perfectly optimized physics computation.
So, what I did was this:
Except main collider used for actual collisions and destruction, every car has two sets of colliders – box and sphere, with sphere colliders being triggers. Note: triggers ensure non-trigger colliders will go through them, and redundancy of colliders on each side ensure
void OnTriggerEnter() will run on every car no matter which one initiated a collision.
Rest is also simple – on every trigger enter event a link between two cars is created if it doesn’t exist yet, link being a simple
struct with two references to cars. Link is placed to a simplest collection possible (I used C# List). On every trigger exit event existence of a link between two cars is checked and link is destroyed if exists.
I find this realization simple and efficient when it comes to something like match-3 games, so if you’re doing one, hope it helps.