- Home /
How to detect collision between 2 objects while checking are they the ones that need to collide?
I've got 4 different color box colliders and 4 blue, red, yellow and green object colliders. I need to make it that when a blue object collider hits a blue box collider, it would give you points, if colors do not match, you would lose.
So any ideas how to detect collision between 2 very specific objects?
you have OnCollisionEnter which passes the other collider. so if yellow got that called and hit a red, it will contain red. you'd need to write the check there. problem is this method is always called on both participants. the easiest would be to give precedence, like yellow handles collisions with all others, red with blue and green and blue with green. green handles none on his side.
I assume the script will be one script for all.
correction: Each box either handles only itself or the other box. That would also do.
Answer by kaosermail · Dec 14, 2018 at 08:28 AM
It's pretty simple. You need to have a script on each object with a function OnTriggerEnter(Collider other) and inside that function check if the colors are the same, or not. For example, for sprites it would be like this:
void OnTriggerEnter(Collider other)
{
if (other.collider.GetComponent<SpriteRenderer>().color == gameObject.GetComponent<SpriteRenderer>().color) {
// here you add points
} else
{
// here you substract them
}
}
Notice that this will add or sub points twice, one for each script.
Thanks for the reply, I'm quite new to this, do you need to tick the "Is Trigger" box on, at the collider component in the inspector pannel? If so, where? On the object which should have the script or on the object which owns (Collider other)? I'm using UI, with a canvas so I'm not using sprite renderer. $$anonymous$$y code is:
void OnTriggerEnter(Collider other) {
Debug.Log("Collided");
if (other.gameObject.name == "GameObjectR")
{
Destroy(other.gameObject);
spawnBalls.score++;
}
else
{
Destroy(other.gameObject);
// load another scene
}
}
But It doesn't do anything, it doesn't even display the message on console.