- Home /
the for statement in unity 3d for iphone
hello!
I want transfer a unity project to iphone platform.
After I deal with #pragma strict and Getcomponent issue ,I found runtime error still happen:
the error message: NullReferenceException: Object reference not set to an instance of an object
the statement:
var gos : Renderer[]; gos = GetComponentsInChildren(Renderer) as Renderer[];
var go : Renderer;
---> for( go in gos ){
go.enabled=false;
}
it seems the original use of "for" can not use in iphone platform,WHY?????
thank you.
Just a $$anonymous$$or note; gos and go mean GameObjects and GameObject. It can become confusing for people working with variable names that tell they are game objects when they actually are components. It doesn't affect your script but the people reading it :)
Answer by Statement · Mar 06, 2011 at 02:56 PM
It's because you're trying to cast a Component[]
to a Renderer[]
, which won't work. The as operator will silently return null if the cast did not work.
Try this instead:
var components = GetComponentsInChildren(Renderer);
for (var component in components)
{
var renderer = component as Renderer; // Renderer is a Component, so it's OK.
renderer.enabled = false;
}
The line of code that was faulty in your provided code snippet wasn't the for loop. It was this:
gos = GetComponentsInChildren(Renderer) as Renderer[];
The cast (as Renderer[]
) would return null
, because Renderer[]
isn't derived from Component[]
and vice versa.
This has nothing to do with iphone. It's just the language syntax.