Instantiate a custom amount of objects on startup to save even more performance #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
With the actual code, if you have a fire rate that allows you to shoot let's say 100 bullets at a time, it will instantiate 100 game objects at runtime for the first shoots. Now if you have different pools running at once like bullets, explosions, coins, power ups, etc (like I have in my game, 7 pools) think about instantiating all these objects when the game is running the first time we need the objects, there is a noticeable frame rate and performance drop during the gameplay, specially in fast paced games.
For that reason I improved the class to allow the pre-instantiation of a defined amount of objects at startup. For the Turrent demo, on startup 10 bullets and 10 explosions are added to the pool and recycled before we even need them, this way when we shoot, the pool will never create another object, since 10 is more than enough to the demo's fire rate.
The magic is in the new CreatePool(T prefab, int initialAmount) and RecycleAll(T obj) methods.
EDITED: CreatePool(T prefab, int initialAmount) now uses SpawnInactive instead of Spawn + RecycleAll.