Foreach listed [C #]

MonoBehavior[] list; // This is from Unity3d but think of it as Object, // all classes inherit from it. 

The list is filled with a lot of things, some of them from Alpha, from the Alpha class, and others from other classes.

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

I was on the assumption that my foreach would work as follows: The Foreach Alpha script found in the list does something, ignores every other component.

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

I get this error at runtime: Unable to apply source type to destination type

+6
source share
7 answers

This is how I do it, and I know for sure that it will compile in Unity3d. OfType is not in Unity, by the way, TypeOf is just like taras.roshko, if you use is better.

 MonoBehavior[] list; foreach(MonoBehavior current in list) // Search the whole list for MonoBehaviors. if (current is Alpha) // Check if current is an Alpha type. current.doSomething(); // current is a valid Alpha type script. 

foreach will try to convert all the elements to a list, and since Alpha is MonoBehavior, but MonoBehavior is not Alpha, you cannot start it correctly. This way you check if the current alpha is, and then if it uses it as you like.

+2
source

You can try something like:

 foreach(Alpha a in list.Where(x => x is Alpha)) // Alpha is a script. a.doSomething(); 
+13
source

You are going to polymorphism by mistake: although Alpha is a derived type, not all other objects in your MonoBehavior type list. Consequently, some will abandon the implicit type that foreach does. You can use the extension "OfType ()" if it is available in your environment:

 foreach(Alpha a in list.OfType<Alpha>()) 
+11
source

use OfType to iterate over only elements of the specified type

+2
source

If you want the loop to work only with Alpha types, you need to rewrite it as follows:

 foreach (var item in list) { if (item is Alpha) { ((Alpha) item).doSomething(); } } 

edit: Maarten's answer uses LINQ, which is more concise, so I would recommend it.

+2
source

your foreach will try to use every object there Alpha . If they have a common superclass, you can use it, otherwise use the Object class.

0
source

If your list contains a list of the base type, and you just take each element and try to think that it is of type Alpha, and not illegal, try below

 foreach(Unity3d a in list) // Alpha is a script. a.doSomething(); 

Assuming doSomething () is not working in Unity3d

0
source

All Articles