Using LINQ in unity games

While the instructor was creating the loop for determining what building is for what building ID, I decided to try and do the same thing using LINQ in C#.

Are you aware of any downsides to using it? Does it limit my compatibility at all?

There is no issue with compatibility using Linq. It’s fully supported in Unity, and it is an extremely powerful tool.
It is, however, a bit resourse intensive, depending on how it’s used. At the very minimum a Linq expression will create at least one new copy of the collection it’s working on. For each clause (.Where, .Orderby, etc), it will create another copy of the collection.
In event driven code (I just clicked on a location, and I need to get the buidling ID), it’s fine (I use Linq a LOT this way), it won’t even be noticeable. In an Update() method (or anything Update calls every frame instead of conditionally), it can grind the gears a bit and slow things down.

3 Likes

Thanks! I didn’t know about the creating copies of the collection! Do you have some documentation somewhere that I can read to learn more about how that happens? I’d like to learn how to avoid that.

No, I remember it from a podcast called Coding Blocks a number of years ago. They were both praising Linq for it’s powerful SQL abilities and critiquing it for the overhead.

In my own experience, I find no negative effects using Linq in event responses, but I’ve tried using it to gather all CombatTargets in the scene in the AI Update loop sorted by distance and affiliation, and in a scene with around 30 AI entities it was a noticeable hit to the FPS.

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

Privacy & Terms