CompareTag to multiple GameObjects

I have multiple gameobjects that spawn randomly prefabs and I wanna do some actions when every gameobjects detects collision. I’ve tried with CompareTag but it didn’t work.

	IEnumerator waitSpawner()
	{
		yield return new WaitForSeconds (startWait);
		while (!stop)
		{
			float spawnLocation=Random.Range(0,0);
			randEnemy = Random.Range (0, 2);
			Vector2 spawnPosition = new Vector2 (spawnLocation,transform.position.y);
			bulletclone=Instantiate (answers [randEnemy], spawnPosition, Quaternion.identity) as GameObject;
			yield return new WaitForSeconds (spawnWait);
		}
	}

This is from the first script when the prefabs are randomly spawn.

void OnTriggerEnter2D(Collider2D col)
	{
		if(col.CompareTag("Correct"))
			{
				test.text="Corect";
			}
		else if(col.CompareTag("Wrong"))
			{
				test.text="Wrong";	
			}
	}

I don’t get any error or warning, just doesn’t work.

Your logic in the OnTriggerEnter2D is wrong. I actually have no idea what CompareTag does as I’ve never used it, but I do know how to do what you’re trying to accomplish.

Instead of using Compare Tag, it is much cleaner if you simply just check to see if the collider’s tag matches the tag you want, which I assume is what you are trying to get the script to do.

 void OnTriggerEnter2D(Collider2D other)
 {
     if(other.tag == "Correct")
         {
             test.text = "Correct";
         }
     else if(other.tag == "Wrong")
         {
             test.text = "Wrong";    
         }
 }

Please also note that it is common practice to use the variable ‘other’ for any collision/collider data in those Collision or Trigger Enter function. However, this is not required.

If this solved your problem, please accept my answer :slight_smile: