The IEnumerable

Why does he use a foreach loop over IModifyProviders in the GetAdditiveModifier in basestats. is there one for each script that implements the interface?

And he says the IEnumerator can work as a list. When we call the IModifierProvider’s GetAdditiveModifier function, does it then call all the functions in the scripts that implemented this method and if the stat is correct returns none, one or a list of floats?

Yes. when we call GetComponents<IModifierProvider>() here, we get all the components on this game object that implements the IModifierProvider interface.

It can be used as a list, but IEnumerable does not provide things like Count or Length because it executes as required and does not know how many times it will execute before it has run out of items.
Linq provides extensions that will execute through all the items and you can use .ToList() from Linq to create an actual list of float values. You can also create a new instance of the list and pass it the IEnumerable as a source

using System.Linq;
// Make a list using Linq
List<float> fromLinq = provider.GetAdditiveModifier().ToList();

// Make a list with the constructor
List<float> fromNew = new List<float>(provider.GetAdditiveModifier());

We do not call the IModifierProvider's GetAdditiveModifier function, we call a class that implements the interface’s GetAdditiveModifier function so no, we do not call all the functions in the scripts that implement this method, only the one on the instance we are referencing. The first foreach gets instances of classes that implements the interface. We then take each instance and call the instance’s implementation of the function.

If the stat is correct it will yield a value, perhaps more. Like Sam mentioned you can yield multiple values and - in the case of the foreach he wrote - we will get each value one at a time. If you create a list from it (either using Linq or passing it into the constructor) it will only contain the values returned by the instance being referenced, not all the available instances although there are ways to do that, too, which I’m not going to go into now.

1 Like

thnx man! that cleared it up

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms