Get script component from all children

 I have a problem about to get script component from....let's say 21 children of 1 game    object

My problem is "impactPointScripts = GetComponentsInChildren(ImpactPoint);"

it say "cannot cast from source type to destination type"

How do i fix this???

     //This is InmpactPointCheaker script, it is in parent gameobject.

private var impactPointScripts : ImpactPoint[];

function makeImpactPoint()
{   
      impactPointScripts = GetComponentsInChildren(ImpactPoint);

      for (var child : ImpactPoint in  impactPointScripts) 
      {
       child.showImpactPoint();
      }

}

___________________________________________________________________
   // this is ImpactPoint script

     function showImpactPoint()
        {

             if(isImpactPoint > 6)
         {
              //turn to red
              iTween.ColorTo(gameObject,{"color" : Color.red,"time": 1});   

              //increase number of impact point at Wall 
                   myparent.increaseNoOfImpactPoint();
         }

        }

_______________________________________________________________________

@Peter G It say "Object reference not set to an instance of an object" it say about for (var child : ImpactPoint in impactPointScripts) { child.showImpactPoint(); }

@Jessy i use "impactPointScripts = Component.GetComponentsInChildren.<ImpactPoint>(false);" and it say "null exception"

1 Answer

1

GetComponentsInChildren returns an array of `Component[]`. You need an array of `ImpactPoint[]`.

impactPointScripts = GetComponentsInChildren(ImpactPoint) as ImpactPoint[];

Its also worth looking at this thread.

No longer necessary to be so verbose. http://unity3d.com/support/documentation/ScriptReference/Component.GetComponentsInChildren.ltTgt.html

Even better. Didn't know there was a generic version.