- Home /
OnControllerColliderHit -> GetComponent on collided object not working
I have been researching this for 6 hours. Slept on it, another 2 hours and still no luck. I have never felt so defeated; this problem has to be something so simple and stupid! Here's the skinny:
I have a player GO that is a modified CharacterController ("Player"). It is the parent of a small sphere GO that has a SphereCollider on it ("Weapon"). Any time I try to collect the Enemy script from collisions, I pop 3 generic errors.
I am testing collisions against a Cube primitive that has a BoxCollider and a Rigidbody ("Enemy"). It also contains a script (Enemy.cs) with the basic badguy functions.
Codewise on the Player (parent, CharacterController):
private Enemy enemy;
void OnControllerColliderHit(ControllerColliderHit hit) {
if (hit.gameObject.tag == "Enemy") {
enemy = hit.gameObject.GetComponent(Enemy);
enemy.TakeDamage(25);
}
}
I have also tried:
void OnControllerColliderHit(ControllerColliderHit hit) {
hit.gameObject.GetComponent(Enemy).TakeDamage(25);
}
Throws these errors on the line where I try to GetComponent():
Error CS0119: Expression denotes a
type', where a
variable',value' or
method group' was expectedError CS1502: The best overloaded method match for
UnityEngine.GameObject.GetComponent(System.Type)' has some invalid arguments - **Error CS1503:** Argument
#1' cannot convertobject' expression to type
System.Type'
I get the same errors also trying OnCollisionEnter() attached to the Weapon GO. I learned that the Parent GO has to handle collisions for its children, which led to dropping the OnControllerColliderHit() onto the Player.
Thanks for taking the time to read this. I appreciate any help you can offer. I'm thinking about just not worrying about collisions between the Player and anyone else, un-childing (bastarding?) the Weapon GO and then just enabling it around the player during its animation so it can handle its own collisions.
Answer by Loius · Apr 30, 2013 at 05:14 PM
You need to GetComponent(typeof(Type)). It's weird, yes.
You can also GetComponent.
In unityscript, GetComponent(Type) works fine because it's overall a very lazy language. I mean you don't even have to explicitly cast every single set of digits to float! xD
If you were here right now I'd hug you; thanks!!
The stupid thing? I was so tunnel-visioned that I didn't even bother checking the ScriptReference for GetComponent....I even have correct GetComponents in other parts of the demo.... hahah