This runs fine and does exactly what I want, but if I leave #pragma strict in my script I get a “WARNING: Implicit downcast from ‘Object’ to ‘UnityEngine.Transform’.” This appears to be the correct way of doing this according to the documentation (http://docs.unity3d.com/ScriptReference/Transform.html.) What am I doing wrong here?
for (var child : Transform in this.transform) { //Example with the current gameobject
for (var child : Transform in objectList[i].transform) { //Example with a gameobject array
Edit: Thought I’d add that I’m aware that I can put #pragma downcast to make the warning go away, and I’ve done that before, but I’m assuming that the documentation would not give examples that would cause a warning without explaining anything about the warning.
This is because ‘Transform’ implements the interface ‘IEnumerable’, but not the interface ‘IEnumerable’.
As a result, the objects that come out of it are typed as ‘Object’, and not as ‘Transform’. You’re implicitly casting these objects to ‘Transform’ with your variable declaration being of type ‘Transform’. Because you have pragma strict, a warning is thrown, because this cast is not guaranteed type safe. (Object to Transform is a downcast, an Object has the potential to be any type known, so therefore the compiler doesn’t know if the cast will succeed).
The only way to fix this with out supressing the warning with a pragma, is for unity to implement the IEnumerable interface… which I don’t know why they haven’t.
I guess you could also write an extension method for Transform that returns the members typed correctly. But that comes with the overhead of an extra function call… might as well just accept the warning.
Aah so that’s why. Glad to know it wasn’t something I was doing wrong. I’ll just continue to suppress the warnings as I’ve done in the past. Thanks a lot!