Efficiently share position with many other GameObjects

I have a game with multiple individually controllable player armies and very many enemies. They are all spawned dynamically at runtime. I want the enemies to automatically slowly move towards the nearest player army. They would determine which is closest to their current position and move there. But to do so, every enemy needs to obtain all the player’s armies’ position vectors, which are all continually changing. What is the best way to share these? Get methods? Messages? Public variables? Or something else I haven’t thought of?

Any help would be greatly appreciated.

edit: clarification of the issue

1 Like

“Best” is often not a question you should get hung up on, especially not for such a small little piece of the code, else you’ll never get anything done. Just do what’s easiest. If it becomes a problem later, you can find it when profiling performance and fix it then.

To give you some answer though, in general, try to avoid using the Find method for finding GameObjects. It is a little bit slow (you likely wouldn’t want to call it every frame for every enemy), and if you change the names of objects and stuff down the road, it causes all sorts of fun. My personal preference for finding lists of stuff and then getting some sort of info from them is creating a ScriptableObject for sets of things I need to do that with.

I recommend checking out this classic video: https://youtu.be/raQ3iHhE_Kk?t=2310

That link will take you to a part of the presentation about Runtime Sets. If you aren’t familiar with ScriptableObjects yet, then you may want to watch the full video.

In a nutshell though, this allows you to automatically create lists of “things” at runtime that can be referenced from anywhere. Then on each prefab, you add a script that adds itself to that list in its Start method (or whichever method you need based on how your game works). Then you can tell your enemies to just look at a list of the existing armies, and for each one, check gameObject.transform.position and see how far away it is. You can throttle how often it checks the list in your enemies script, because you don’t likely need to get that info every frame for the enemies to respond quickly enough.

2 Likes

Thank you so much that is very useful