Collision with tag

Lads,
I’m trying to destroy an object when it hits the ground and have a little particle effect instantiate. I’m also trying to use a tag so that this only happens when the object collides with the ground and not other objects… Here’s what I’ve got thus far:

    var explosionPrefab:Transform;

function OnCollisionEnter(collision: Collision) {

if (collision.gameObject.tag == "Ground_Smoke");

Instantiate (explosionPrefab,transform.position,transform.rotation);

Destroy (gameObject);
}

I think I’m in the ballpark, but not quite there yet.
Assistance would be appreciated.

Thx,

Stef

Yeah, you’re very near! If you remove the “;” after the if, your code should work.

But to have better results, you must use the collision point and normal to generate position and rotation for the smoke prefab. The Collision structure has the field contacts, an array of contact points which inform also the surface normal in the hit point; in this case, you can use only the first contact point, contacts[0]:

function OnCollisionEnter(collision: Collision) {
  if (collision.gameObject.tag == "Ground_Smoke"){
    var hit = collision.contacts[0]; // let's get the first contact
    // find the rotation needed to make the smoke perpendicular to the hit surface
    var rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
    Instantiate (explosionPrefab, hit.point, rot);
  }
  Destroy (gameObject); // destroy the projectile anyway
}

Try using
if(col.gameObject.CompareTag(“Name of tag”))
{
//code here
}

This worked for me when having the same problem :slight_smile:

Remove semicolon(:wink: after if statement.

The delete gameobject function is outside of the if statement, meaning that it will destroy if it hits any collider but only instantiate the particle effetc if it hits the ground.

You may be able to try changing it to a trigger instead of a collision. As an example for you I have the following script (which works) in my current prototype.

function OnTriggerEnter (col : Collider) {
    if (col.tag == hitObjectsTag)
    {
        overlord.SendMessage("NoteHit", soundClipNumber);

        Instantiate (dropletPrefab, transform.position, transform.rotation);
        Destroy(this.gameObject);
    }
    if (col.tag  == backWall)
    {
        if (isNotJelly){
            // need to implement a way to change the soundClipNumber depending on the note hit
            overlord.SendMessage("NoteMissed");
            anglerFish.SendMessage("MoveBack");
        }

        Destroy(this.gameObject);
    }
}

hitObjectsTag and backWall are just variables I set as Strings so I can edit them in the inspector.