Why the foreach?

Hey good people

Maybe I’m jumping the gun here, and it will become clear later. But I’m wondering: why the foreach? I think it’s a good thing to highlight (I’m a fan of foreach in other languages.) But as I was writing out the code I was just thinking: have I not just taken a list of transforms, iterated through it to construct a new list of transforms, then returned it? Why not just return the original list of transforms (the variable pathPrefab)? Is it essentially reformatting the object to the correct type?

Thanks

Hi,

Those are good questions. Theoretically, we could have returned the reference to the pathPrefab. However, in object-oriented programming (OOP), that’s considered bad practice because everything that has got a reference to the object assigned to pathPrefab could manipulate it. To prevent that from happening, we create a new list with all waypoints.

If something removes one element from that new list, it won’t affect other parts of our game because we still have the unmodified pathPrefab list.

Did this make sense?


See also:

1 Like

Ah, thank you. That makes sense. I studied OOP many years ago, but in recent years I do more non-OO scripting.

Thanks for your help.

Aled

Unity is a bit tricky in this respect. We do want to follow OOP principles but that’s not always possible. In this case, it was possible.

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

Privacy & Terms