Regarding using Eventhandler here over linq

Hello Hugo, first… got to say, I really enjoy this course. My favorite GameDevTV course without a doubt.
Really opened my eyes for how to use events more efficently.

But… I am wondering, making the two static OnUnitSpawned / OnUnitDead events in the Unit script this episode, is it really necessary?
I mean, why not just use a simple linq query, is there benfits in efficiency with events over finding an object?

            _unitList = new List<Unit>(FindObjectsOfType<Unit>());

            _friendlyUnitList = _unitList.FindAll(u => !u.IsEnemy());
            _enemyUnitList = _unitList.FindAll(u => u.IsEnemy());

This does more or less the same thing, if I am not mistaken?

Ok I regret asking, after thinking a bit more on it, using linq won’t add or remove units dynamically from the list when the unit dies or spawns. :slight_smile:

I love Linq. I eat, sleep and breath Linq. But you have to be careful with Linq in Unity. it creates a lot of garbage. It’s ok to use Linq on occasion, but you want to avoid using it in an Update loop, for example. With the lists mentioned above, there is no guarantee that they will not be accessed from an Update loop somewhere, so it is best to avoid it

3 Likes

Point taken, I also love linq. I use Linq daily in my work, list manipulation is just waaay easier with it. ^^

1 Like

You could still use that if you really wanted to just keep a single list. You would only need to keep the unitList then create a new list when some script asks for just the friendlies or enemies.

However like @HrolgarUllr mentioned be aware that constantly creating lists, (and using Linq in general) will generate quite a bit a garbage. If you only do it regularly then it’s not necessarily an issue but do keep that in mind.

Personally I find using multiple lists better than generating them on the fly but yup that is also a valid alternative.

2 Likes

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

Privacy & Terms