- Home /
Detect collision with specified object
I was trying to use OnCollisionEnter, I know it detect collision on every object with collider, I want to specify which object it will detect collision with. How I do it in java script?
Answer by RoughDesign · Sep 23, 2011 at 05:26 PM
You can use something like
function OnCollisionEnter(Bam : Collision)
{
if(Bam.collider.gameObject.name == "whatIWannaHit")
{
//What you wanna do on collision with GameObject "whatIWannaHit"
}
}
However, if you want achieve something like 'only hits enemies', it might be more convenient to use tags. You can for example create a tag named "enemy" and tag all enemy GameObjects with that. Then you can check for the tag like that:
function OnCollisionEnter(Bam : Collision)
{
if(Bam.tag == "enemy")
{
//What you wanna do on collision with GameObject tagged "enemy"
}
}
You don't need the 'collider.gameObject' in your if statement.
if(Bam.tag == "enemy")
is enough.
I took some of my time and provided a working solution here.
I didn't know the collision is also tagged the same as the GameObject that collides. Yeah, I'm still learning.
Then you provided a way to use less resources, which is nice of you.
But is that a reason to vote me down like a spammer?
Not that I'm hunting for karma or something, that just seems rude.