How to check if tag collides with identical tag
So i have objects that are spawning that contain different tags, the goal is to drag the objects to the same color, and not any other color. what i currently have is working fine, but i just want to clean up the code and turn 4 scripts into one. how do i detect if a tag collides with an object with the same tag?
here is my current code, there is 4 identical scripts with different tags listed. hope this makes sense. thanks in advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class YellowCollide : MonoBehaviour
{
public AudioSource pop;
// Start is called before the first frame update
void Start()
{
pop = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Yellow")
{
pop.Play();
Destroy(gameObject, 0.1f);
ScoreManager.instance.IncrementScore();
}
else if (col.gameObject.tag == "Red" || col.gameObject.tag == "Blue" || col.gameObject.tag == "Green")
{
SceneManager.LoadScene("Lose");
}
}
}
Answer by streeetwalker · Mar 25, 2020 at 08:22 PM
If( this.gameObject.tag == "someTag" && col.gameObject.tag == "someTag" )
// don't need the keyword 'this' - but you can use it to make the reference explicit
// or if you want to test directly:
if( gameObject.tag == col.gameObject.tag )
You don't need the keyword 'this' you can just write gameObject to reference the object that this script is attached to.
Your answer
![](https://koobas.hobune.stream/wayback/20220612225517im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to change the alpha of every GameObject with the same Tag ? 1 Answer
How do i make a game object grow by absorbing another game object ? 0 Answers
How can I make sure that the gameObject that collides with the FPSController is the one I need? 0 Answers
Having trouble moving a GameObject to another scene and Transform it to a different position 0 Answers