Using different paricle emitters depending on the tag of the object raycast hits?

I'm creating a FPS game and using raycast to detect collisions when the player fires a weapon. As it hits something a particle emitter emits a particle looking like a plaster wall puff. However it's the same for when it hits glass, wood and flesh, the raycast is handled in the player weapons script.

I would like it to use different particle emitters for objects with different object tags (eg. Enemy, Water, Glass etc, and of course I have created such particle effects aswell.) I've spent 3 days trying to make the raycast to detect the collisions tag but I'm not very experienced with coding and obviously I get it wrong over and over again. Would really appreciate some help on this, feels as if I've walked into a dead end.

First, make sure you're using a version of Raycast which includes passing results to a RaycastHit object. The first example in the Raycast Documentation doesn't do this, but the second example does.

Next, simply check the 'tag' variable of the collider that was hit, eg:

var hit : RaycastHit;
if (Physics.Raycast (origin, direction, hit, distance)) {
    if (hit.collider.tag == "Glass") {
        // ...use glass particles...
    }
}

If you're creating a number of different types of surface, you'll end up with lots of 'if' statements in there though, or a switch statement, neither of which are really desirable because you'll end up with hard-coded values which need modifying if you add or change your particles or surfaces. A neater way of setting this up would be to have the code itself check whether there's a suitable emitter for whichever surface was hit:

  • Create a public ParticleEmitter array variable, which you can then populate in the editor, like this:

    var surfaceHitEmitters : ParticleEmitter[];

  • In the Editor: Assign the correct length to the array

  • Drag each particle system type into a slot in the array

  • Assign your tags ("Water", "Glass", "Wood" etc) to the emitter objects too

You can then check at runtime whether there's a suitable emitter for the type of surface hit, without much fancy coding at all:

var hit : RaycastHit;
if (Physics.Raycast (origin, direction, hit, distance)) {
    for (var emitter : ParticleEmitter in surfaceHitEmitters) {
        if (emitter.tag == hit.collider.tag) {
            emitter.Emit();
            break;
        }
    }
}

The above code scans through the emitters in the array, and calls Emit() on one if it finds that it has a tag that matches the type of surface that was hit (this is why you need to tag the emitters as well as the surfaces in your scene).

You could probably optimise this by making a lookup table using a Hashtable or some other key-value lookup system. You could also remove the need to assign tags to everything altogether by picking the appropriate emitter based on the Material of the object hit.