- Home /
The question is answered, right answer was accepted
Pragma Strict - Implicit Downcast from 'Object' to 'UnityEngine.Transform'
Hey there, I've just been taking to my scripts with #pragma strict, and overall they've done pretty well in terms of an absence of instances of dynamic typing. There is one instance which is boggling me though, and that is this line:
for(var child : Transform in transform) {
child.gameObject.layer = 8;
}
I am getting the error BCW0028: WARNING: Implicit downcast from 'Object' to 'UnityEngine.Transform'. My first thoughts were, isn't child being typecasted to a Transform by using var child : Transform? But now I'm not so sure. I've tried using as Transform in various places but to no avail.
What is the correct way of typecasting this?
Thanks, Klep
Answer by Eric5h5 · Mar 12, 2012 at 10:42 AM
That's fine. It's just a warning, not an error, in case you didn't mean to do that, but I don't think there's a way to avoid it when doing "for (x in transform)". You can use #pragma downcast to suppress the warning.
It is being explicitly cast; read the question again and look at the code.
No it's not!
He needs to cast transform to Transform[]. That gets rid of the warning without ignoring it
You can't cast transform to Transform[]. The code might compile but it wouldn't actually work at runtime.
Answer by devGuillaume · Apr 17, 2012 at 03:30 PM
AndyZ has a workaround:
for(child in transform)
{
var typedChild : Transform = child as Transform;
typedChild.gameobject.layer = 8;
}
I don't know if there is any downside to it though.
Answer by elegize · Jan 09, 2014 at 02:24 PM
What works for me:
for (var i = 0; i < transform.childCount; i++)
{
transform.GetChild(i).gameObject.layer = 8;
}
Answer by Eilijah · Oct 04, 2013 at 11:09 AM
var children : Component[] = transform.GetComponents(Transform);
for (var child : Component in children) {
var typedChild : Transform = child as Transform;
typedChild.gameobject.layer = 8;
}
Please read the question before posting, and also make sure your code actually fixes the OP's problem. Right now you're not even accessing the transforms children. transform.GetComponents(Transform) is the same as writing [transform].
Answer by hyperback · Sep 07, 2014 at 06:11 PM
var children : Component[] = transform.GetComponents(Transform);
for (var child : Component in children) {
var typedChild : Transform = child;
typedChild.gameobject.layer = 8;
}
this one will work ^^
It won't work...`for (t in transform)` iterates through all children, but GetComponents(Transform) does not get any children. devGuillaume already posted the best answer.
Follow this Question
Related Questions
Implicit downcast and ArrayList 1 Answer
Implicit Downcast Warning and Converting Arrays 2 Answers
How to set a Transform variable with code (C#) 3 Answers
Perpendicular forward :-) 0 Answers
Third person Camera stop it from going lower than the terrian 0 Answers