foreach Element Problem

public Component list;

list = GetComponentsInChildren<Component>();

foreach(Alpha a in list) // Alpha is a script.

I want to destroy all the Alpha scripts in that list of components. I was under the assumption that my foreach would work this way: Foreach Alpha script found in list do something, ignore every other component.

This is a casting problem, I think. Please help me understand casting/polymorphism better.

foreach simply iterates through all elements in list. Since you typed the iterator variable as Alpha it will throw a casting exception for each element that isn’t of type Alpha. foreach does not sort or filter anything, it just iterates through the collection.

If you want to use a Component array (for what reason ever), you can do something like this:

foreach(Component c in list)
    if (c is Alpha)
        Destroy(c as Alpha);
        // or
        // Destroy((Alpha)c);