Saturday, June 23, 2018

unity - Is it more efficient to add scripts to each GameObject or to a single parent object?


Does a C# script added to a parent object work more efficiently and effectively (in terms of both memory and performance) on all objects, in my case lighting, or adding script components to each lighting/GameObject object? This goes for other GameObjects parented in the hierarchy.



Answer



There is some amount of overhead to invoking each script's Update() and other methods, compared to maintaining a list of objects and updating them all at once from a single entry point.


So, if you maintain a list of multiple objects to update, you may see some runtime efficiency wins by iterating over them from within a single script instance. Just note that if you're searching for instances to update using FindObjectsOfType or GetComponentsInChildren, the search cost will likely outweigh the savings of not invoking each one's Update separately. So look for ways that you can persist the list across frames rather than re-building it continuously.


In practice, I haven't experienced noticeable slowdowns from having dozens and dozens of instances of simple scripts updating independently, so I recommend profiling first before adding complexity to your project - it may be premature optimization for many applications.


You should also weigh whether your developers may gain iteration efficiency by keeping the instances separate. This can make it easier to individually select & tweak a single instance or group of instances, or make use of prefabs and object references. These operations can get more complicated if the needed methods & data are tied up in a higher-level manager script.


Which pattern makes more sense for a particular feature will depend a lot on the specifics of what you're trying to accomplish, what workflows your team likes to use, and what your performance profiling looks like.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...