Help With Adding a Tag To Script

I’m creating a game and I am new to coding, I just can’t figure out how to add a tag to the following explosion on collision script, so if somebody could help, that would be great, (I found this on the internet).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ExplosiononCollision : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
   
    public GameObject explosion;

    void OnCollisionEnter()
    {

            GameObject expl = Instantiate(explosion, transform.position, Quaternion.identity) as GameObject;
            Destroy(gameObject, .1f);
            Destroy(expl, 5);
    }
}

Thank You

You can assign a tag from the script like this:

myCrazyObject.tag = "Enemy";

HOWEVER, you must have defined that tag in the Tag Manager before you can use/assign it.

What do you mean “add a tag”?, please provide more info

you mean only trigger if for example an object tagged “player” hits the collider?
if so - it’s like this:

void OnCollisionEnter(Collision col) //get the collision parameters too
    {
            if(col.gameObject.CompareTag("Player")) //check if object is "xxx"
                 return; //if true - exit function
            GameObject expl = Instantiate(explosion, transform.position, Quaternion.identity) as GameObject;
            Destroy(gameObject, .1f);
            Destroy(expl, 5);
    }

When I said add a tag, I meant I wanted the explosion to happen when it collided with the object using that tag. I tried the code but it caused the object to explode whenever it touched anything but the assigned tag.

So just negate the expression in the if statement.

Could you explain more, as I am still new to coding.

if(!col.gameObject.CompareTag("Player"))

Which means it will return if the collision happens with anything but the player.
So the explosion Instantiate will run when the collision happens with the player.

1 Like

Thanks everybody for the help, I got the game working.