I know I can use OnCollisionEnter to detect collisions, but what if I want to detect collisions with an object of a certain tag? I’ve searched but can’t find anything.
Joey.
I know I can use OnCollisionEnter to detect collisions, but what if I want to detect collisions with an object of a certain tag? I’ve searched but can’t find anything.
Joey.
If you want to detect the collision with a certain tag obj. Just simply add a line of code.
i.e
function OnCollisionEnter (col : Collision) {
if (col.gameObject.tag == “whatever the tag is” ) {
print (“hooray”);
}}
Make sure that the object tag mush be the same as the name of the tag you write in the script. Even though wrong in capital letter can result in error ! Hope this helps!
Please post code in code tags, it makes it much easier to read.
function OnCollisionEnter (col : Collision) {
if (col.gameObject.tag == "whatever the tag is" ) {
print ("hooray");
}
}
Don’t you agree?
In other news, henry96 got it spot on though GameObjects do have a CompareTag function which does the very same thing. I of course use the solution above, its a matter of personal preference in this case.
I agree! I also want to put in code tag. But I am on mobile so I can’t do that. Hehe
Alright thanks guys. I wish I could code, but modeling is my thing.
Hi Joey – just browsing the forums and this thread caught my eye. Another option I encourage you to browse in the docs is Layer-based collision. If you are familiar with photo-editing software (as a modeler I suspect you are
) just visualize the game at runtime organized that way. Layers then equating to things like “Player Projectiles”, “Environment”, “EnemyType1” etc and can be customized in the editor as you like. (This approach works identically as applied to OnTriggerXXXXX events as well)
For example, an explosive “enemy” mine floating through space could have this script applied to it:
private void OnCollisionEnter (Collision other)
{
// For debug only, remove from release code
Debug.Log("Mine Collision with " + other.gameObject.name);
switch(other.gameObject.[B]layer[/B])
{
case 8:
// Player layer: destroy self, impart damage to player
break;
case 9:
// PlayerProjectiles layer: destroy self
break;
case 10:
// Enemy Mine layer: ignore since we don't want mines blowing themselves up
break;
default:
break;
}
}
Last key point about layers is the declarative collision avoidance matrix. Most useful for controlling both behaviors and time spent inside the physics engine. (see link)
HTH
http://unity3d.com/support/documentation/Components/Layer%20Based%20Collision%20detection.html