- Home /
How to count collisions of the same tagged objects?
I couldn't find an answer to this.
I have multiple prefabs in my scene and they have all the same tag. Now I want to update my score based on colliding of these prefabs together. Currently it works only, if those prefabs collide with another prefab, which has different tag.
How can I count the collisions of the same shared tag prefabs? a short explanation will be very appreciated.
Answer by Llama_w_2Ls · Jan 29, 2021 at 07:36 AM
You can use the method GameObject.CompareTag(string tagName);
to compare the tags of the two objects in the collision. It returns true if the tags are the same. For example:
public int score;
void OnCollisionEnter(Collider collision)
{
// if tag of collided object is the same as my tag
if (collision.collider.gameObject.CompareTag(tag))
{
score++;
}
}
Ok, I managed it somehow. looks like this:
public void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Square")
{
squareCollisions++;
score.text = squareCollisions.ToString();
if (squareCollisions > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", squareCollisions);
highScore.text = squareCollisions.ToString();
}
}
}
Now, this count appears for each tag separately. I mean if there are three objects A,B,C and all has the same tag. now if A collides with B, two times, the score updates to two. then If A collides with C one time, the score goes back to 1 and so on counts the collisions. I want to count all these collisions and store them in score.text. Is that possible?
you have to give them all unique tags or use the gameObject.name or object type, which would use 3 variables and would be more if you wanted more objects. It might be better to have the collision count a part of the square object script. So
if (other.gameObject.tag == "Square")
other.gameObject.GetComponent<YourScript>().collisions++;
then all the objects keep track of the collisions themselves.. however the get component may slow things down.. You could put the collision on the square script rather than the player to avoid getComponent call.
Answer by Hefaz · Feb 01, 2021 at 07:49 AM
OK. so I solved the problem by adding another separate script, called GameManager, where I updated the score text.
It was not working here, because, both the player and the square prefabs, had the same script shared for collisions. I hope this helps someone.
Your answer
Follow this Question
Related Questions
1 Button Alternating Between 2 onClick Functions 1 Answer
How can i look for collisions of the bulidngs in may array ? how can i use OnTRiggerEnter/exit ? 0 Answers
Playing certain sound during collision 1 Answer
OnMouseDown with colliders behind the object being clicked 3 Answers
Collision reaction not working 2 Answers