- Home /
Why do I get invalid cast with this code?
var zombieLimbs:Transform[];
zombieLimbs= gameObject.GetComponentsInChildren(Transform);
for(var limb :Transform in zombieLimbs)
{
//Do something here
}
It's practically the same code as the documentation except theat the documentation uses a hingejoint component instead. ???
The error is: invalidCastException: Cannot cast from source type to destination type.
Answer by MFen · Nov 05, 2013 at 01:37 PM
try this instead:
zombieLimbs= gameObject.GetComponentsInChildren(Transform)as Transform;
Nope. If I try:
var zombieLimbs:Transform[];
zombieLimbs= gameObject.GetComponentsInChildren(Transform)as Transform[];
for(var limb :Transform in zombieLimbs)
{
//
}
I get a the following error: NullReferenceException: Object reference not set to an instance of an object
..and if I do
zombieLimbs= gameObject.GetComponentsInChildren(Transform)as Transform;
I get Cannot convert 'UnityEngine.Transform' to 'UnityEngine.Transform[]'.
Answer by aldonaletto · Nov 05, 2013 at 04:25 PM
GetComponentsInChildren returns Component[]. Change to this:
var zombieLimbs: Component[];
zombieLimbs = gameObject.GetComponentsInChildren(Transform);
for(var limb :Transform in zombieLimbs){
// do something
}
NOTE: This code returns all transforms down in the hierarchy, including this object's transform and all its grandchildren, if any. If you want only the child transforms, the code should be like this:
for (var child in transform){
// child in this case is Object - convert to Transform in limb:
var limb: Transform = child;
// do something
}
Your answer
Follow this Question
Related Questions
Get SkinnedMeshRenderer as Renderer? 1 Answer
GetComponentsInChildren Problem 1 Answer
Invalid Cast error when my format seems the same as the script reference example? 1 Answer
GetComponentsInChildren contains null elements when fetching MeshRenderers 1 Answer
Is it not possible to include "if-then" conditionals within foreach loops? 1 Answer