Home > Software engineering >  Change a gameObject tag if he's in a collision (OnTriggerEnter/OnTriggerExit)
Change a gameObject tag if he's in a collision (OnTriggerEnter/OnTriggerExit)

Time:01-23

Im programming a rythm game, if a circle enter a specific zone, the player can press Space to make the circle disappear (I can already do that), but I have a problem when there is multiple circles in the scene, I can't difference them. So I want to change the tag of a specific circle if he enter's a specific zone.

Here is my code (is working with only 1 circle in the scene):

using UnityEngine;

public class CursorPress : MonoBehaviour {

    public bool canBePressed;
    public KeyCode keyToPress;
    public Animation anim;


    void Update()
    {
        if (Input.GetKeyDown(keyToPress)) // if the player press a specific button
        {
            GameObject target = GameObject.FindGameObjectWithTag("Target"); // searching tag
            if(target.tag == "Target") // kinda useless lol
            {
                if (canBePressed)
                {
                    anim = gameObject.GetComponent<Animation>();
                    anim.Play("hitcircle_fading"); // error the animation couldn't be found
                    Destroy(target); // we destroy the circle
                }
            }
        }
    }
    void OnTriggerEnter2D(Collider2D col) // turning canBePressed true
    {
        if (col.gameObject.tag == "Target")
        {
            canBePressed = true;
        }
    }

    void OnTriggerExit2D(Collider2D col) // turning canBePressed false
    {
        if (col.gameObject.tag == "Target")
        {
            canBePressed = false;
        }
    }
}

(you can ignore the fading animation, it doesn't work lol. unity gives me this error : The animation state hitcircle_fading could not be played because it couldn't be found! Please attach an animation clip with the name 'hitcircle_fading' or call this function only for existing animations.)

CodePudding user response:

You can simply change tags with col.gameObject.tag = "anotherTag" given "anotherTag" has been added in the editor. Dont forget to set the tag back when the circle leaves the trigger area.

But it would be more common to keep a reference to the circle in question so there would be no need to do GameObject.FindGameObjectWithTag("Target"); which is potentially expensive.

GameObject target;

void Update()
{
    if (Input.GetKeyDown(keyToPress)) {   // if the player press a specific button
        if (target != null) {
            // your anim stuff
            Destroy(target); // we destroy the circle
        }
    }
}

void OnTriggerEnter2D(Collider2D col)
{
    target = col.gameObject;
}

void OnTriggerExit2D(Collider2D col)
{
    target = null;
}

}

If more than one circle can enter the trigger zone, you can change GameObject target to a list for example and extend the rest of the code appropiately.

  • Related