- Home /
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.
Answer by Yoshinator2 · Aug 02, 2017 at 12:33 AM
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 :)
It doesn't work, notice that the prefabs contains those tags.
So you're comparing tags on prefabs that haven't been spawned yet..?
It was my fault, I forgot to pot collider2D on prefabs. It works with other.tag== "Correct"
and compare tag too. Thanks for info.
Your answer is actually misleading. CompareTag is the preferred way to compare the tag of a gameobject as it doesn't allocate any memory. When you read the ".tag" property manually, Unity has to create a managed string which is returned by the property. CompareTag does perform the comparison on the native code side without the need to pass the object's tag value into the managed world.
Wow ok, thanks for the info! I never knew that, I'll use that from now on. Thank you :)