- Home /
C# getComponent result error cast
this is a line of code to get a component in children, every time i use this "getComponent", "getComponentInChildren", etc. there is an error always come up "cannot convert type 'UnityEngine.Component' to 'UnityEngine.ControllerColliderHit'" or else up to the type. i don't understand why, and as long as i see, it's very easy to do on JS than on C# even with a force cast..
ControllerColliderHit hitObject = (ControllerColliderHit)transform.FindChild("EnemySight").GetComponent(typeof(ControllerColliderHit))
what i know if this getComponent function suppoe to return as the type. anyone knows why..?? thx.
Answer by Eric5h5 · Dec 04, 2012 at 10:41 PM
You need to cast it properly; you're doing the casting in the wrong place:
hitObject = transform.FindChild("EnemySight").GetComponent(typeof(ControllerColliderHit)) as ControllerColliderHit
Or else use the generic version:
hitObject = transform.FindChild("EnemySight").GetComponent<ControllerColliderHit>()
The non-generic GetComponent returns the type of the component rather than Component in Unityscript (as long as you don't use a string), but not in C#.
Answer by bompi88 · Dec 04, 2012 at 10:43 PM
About a year without Unity, but I think I remember that you could do something like this:
ControllerColliderHit hitObject;
hitObject = transform.FindChild("EnemySight").GetComponent<ControllerColliderHit>();
Answer by Bunny83 · Dec 05, 2012 at 12:08 AM
ControllerColliderHit is a struct and is not derived from Component. It's only use is as parameter for the OnControllerColliderHit callback.
This cast is not possible since ControllerColliderHit is something totally different as a Component. I'm not sure what you actually want to do, i guess you want to access the CharacterController (which is a Component).
I suggest you take a look at the inheritance tree to see which class is derived from what.
actually, i need to know when the child collided to certain collider. how do i suppose to do then..??
A child? Of a charactercontroller? That doesn't work since the Charactercontroller don't uses physics. It only checks it's capsule collider. Use a Rigidbody ins$$anonymous$$d. $$anonymous$$eep in $$anonymous$$d that a Rigidbody works a bit different than a CC.
a child of a game object (gameObject inside gameObject) which has it's own collider
yes, as i said it doesn't work with a CharacterController. You have to use a Rigidbody to detect collisions with other colliders. The CC can only use it's own capsule.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Problem when Getting a component from a non Mono Behavior class. 1 Answer
Problem calling variable across scripts (Closed) 1 Answer
error CS0118: `New_Career.Fame' is a `field' but a `type' was expected 1 Answer
Float to int casting in C# script with modulo giving division by zero error 1 Answer