- Home /
GetComponent on Collider not working
I'm working on a way to allow the player to kill monsters/destroy barricades. I have it mostly complete but for some reason, this one script isn't working how it should.
void OnCollisionEnter ( Collision c ){
if (weaponType == WeaponType.Missile) {
if (c.gameObject.GetComponent<Damageable>() != null) {
Debug.Log("yes");
Damageable damageable = c.gameObject.GetComponent<Damageable>();
damageable.ApplyDamage( damage );
}
Destroy(this.gameObject);
}
}
I have a gameObject with the Damageable script attached and I know the collision script runs because the bolt destroys itself (the second line runs perfectly) on collision but the Debug.Log function isn't run.
If someone could tell me why the second If statement doesn't run and how I would make it work, I would greatly appreciate it.
Is the collider on the same GameObject as the Damageable component or on a child GameObject?
As a side note - don't use GetComponent in if, only to call it again 2 lines later, in case when you hit correct object. Just use
Damageable damageable = c.gameObject.GetComponent<Damageable>();
if(damageable != null)
{
damageable.ApplyDamage(damage);
}
Try using c.collider.gameObject.GetComponent()?
$$anonymous$$ight be that c.gameObject is the wrong gameObject in the collision. Print out its name so you know for sure. Otherwise, I'm at a loss, script looks fine save for @ArkaneX's suggestion.
$$anonymous$$ight I also suggest a coding convention? Damageable sounds like an interface type, like IDamangeable. You should either make it an interface, and implement it whenever you need something that is damageable, or rename it to something more specific/descriptive, without the "-able" suffix.
Answer by salex100m · Dec 19, 2013 at 02:15 AM
right before your " if (c.gameObject.GetComponent() != null) " line, put this statement:
Debug.Log (c.gameObject);
what does it output as?
I already tried that. It outputs the gameobject wih the script on it. I'm starting to think that this is a Unity bug.
Try destroying the object after a few seconds (like 5 seconds or something really long).
Answer by murrayk012000 · Jul 25, 2017 at 08:15 PM
I'm hitting this same issue. Inside the IF statement the GetComponent method seems to return null. If I call GetComponent before the IF statement and compare against that then it works.
Your answer
Follow this Question
Related Questions
OnTriggerEnter issue 1 Answer
Player object still gets destroyed even when shields up 1 Answer
Creating a Switch that Controls a Gate 1 Answer
Score added on collision with another player 0 Answers
desrtoying on collision 1 Answer