How to efficiently 'destroy' and re-spawn objects using a stack (more efficient than an array) for thousands of objects.
I show you how to iterate over (look through) the stack of objects using a foreach loop. We also explore how to fetch data/variables from other scripts, how to create prefabs, and how to reposition game objects when they are re-spawned inside a random unit sphere.
We also improve the accuracy of our laser (from the previous video: • Unity tutorial: script a laser with L... ) with the ScreenToRay Camera function (see previous video for how to create this functional laser effect).
See below for a few suggestions on improvements, and something I forgot to cover in the video.
Thanks for watching!
Notes:
1)
It would be more efficient to check for inactive objects for re-spawning ONLY each time we fire the laser -- instead of every single Update(); the logic being, only after the laser is fired is there a chance of the objects being set to inactive.
2) I forgot to look at re-spawning objects once they have moved far enough, or have reached a certain distance away from the player. So here's one line of code that will achieve that:
if (n.transform.position.z == -1000f) { n.activeSelf = false;}
This should be placed in the foreach loop, where we are moving the droplets negatively along the z axis. I've had to use == here instead of the safer and more logical idea of a backwards 'less than' arrow, only because you can't use the backward-arrow in the Youtube description :)
Another method would be to measure the distance between the player's position and the droplet's position:
if (Vector3.Distance(player.position, n.transform.position) [GREATER THAN ARROW] 300f) { n.activeSelf = false;}
Same issue with the forwards-arrow :). The Vector3.Distance function measures the distance between two Vector3 objects -- in this case our droplet's position and the player's position. If this is greater than a certain amount (I've just chosen 300f), then set the droplet to inactive.
Handy that as soon as inactive, our code already takes care of re-spawning them at the desired location.
Watch video (Rambling) Unity Tutorial: Easy Object Pooling using a Stack online without registration, duration hours minute second in high quality. This video was added by user Red Hen dev 10 April 2020, don't forget to share it with your friends and acquaintances, it has been viewed on our site 387 once and liked it 11 people.