Unity 2021 Object Pool API - What is Object Pooling and How to Use the NEW API

  Рет қаралды 11,691

LlamAcademy

LlamAcademy

Күн бұрын

Get an in-depth overview of the most commonly needed functionality of the Unity Object Pooling API (UnityEngine.Pool namespace) introduced in the 2021 version of the Unity Editor.
In this video you'll learn:
🧰 What Object Pooling is
🧰 Why you need Object Pooling
🧰 How to use the 2021 Object Pooling API
🧰 Some things I wish were included in the API, but are not
The key benefit of having a built-in API for object pooling is you no longer have to roll your own solution, nor purchase one from the asset store! Unity now provides a high performance, easy to use API to pool all kinds of things!
💸 Ongoing sales 💸
⚫ See all active asset sales on the Asset Store: assetstore.unity.com/?on_sale...
⚫ Save 25% off your first Asset Store Order: prf.hn/click/camref:1101l9QvC...
⚫ Save up to 50% on NEW Assets: assetstore.unity.com/?new_sal...
👨‍💻 As always, all code from this video is available on GitHub: github.com/llamacademy/2021-o...
❤ Believe in LlamAcademy's mission and have received value from the videos? Become a Patreon Supporter or KZbin Member:
⚫ Patreon: / llamacademy
⚫ KZbin Member: / @llamacademy or click the Join button on any video
----
Most tutorials come from knowledge gained making survival.llama.software Llama Survival - a top-down zombie survival shooter for Android and iOS.
I also have some Unity Assets (affiliate link): assetstore.unity.com/publishe...
Some links may be affiliate links, which at no additional cost to you, gives me a small portion of the purchase.
#unitytutorial #tutorialtuesday #gamedev #tutorial #unity #llamacademy #gamedevelopment #optimization
Chapters:
00:00 What is Object Pooling and Why Do You Need it?
01:51 Using the New API
02:38 Object Pool Constructor & Callbacks
04:41 Scene Overview
05:29 Bullet.cs
07:10 BulletSpawner.cs - Variables
07:50 BulletSpawner.cs - Spawning Bullets Without a Pool
10:26 Scene & Physics Setup
11:18 Demo and Profiling No Object Pool
11:56 Bullet.cs - Converting to Support Destroy or Disable
12:17 BulletSpawner.cs - Adding an Object Pool
15:42 BulletSpawner.cs - Using Pooled Bullets
16:00 BulletSpawner.cs - Showing Pool Stats
16:25 Performance Comparison and Improvements I'd Like to See In The API
18:45 Closing

Пікірлер: 61
@TChrisBaker
@TChrisBaker Жыл бұрын
This helped me so much. It worked perfectly in my project
@FaebuOG
@FaebuOG Жыл бұрын
Man if I wouldnt be broke you would instantly have my money for your patreon. I appreciate your videos a looot. Helped me so much
@LlamAcademy
@LlamAcademy Жыл бұрын
🤗 I appreciate that. I know not everyone is in a position to provide monetary support, but I believe that shouldn't prevent you from getting the full value! I hope the content continues to help you on your journey!
@FaebuOG
@FaebuOG Жыл бұрын
@@LlamAcademy It helped me getting a fucking good grade ❤️
@beng758
@beng758 Жыл бұрын
$= string @16:12 was a tiny detail i wasn't aware about. coool :)
@LlamAcademy
@LlamAcademy Жыл бұрын
Yeah that’s super helpful when you’re trying to use especially multiple variables in a single string!
@sanded9321
@sanded9321 Жыл бұрын
Why are you using the box collider for the bullet? Wouldn't the sphere collider be faster?
@Mr_CROWdelusion
@Mr_CROWdelusion Жыл бұрын
I love your Tutorials, discovered this channel a week ago or so and already helped me a lot! a side note: as i got to this video by your weapon-SO-videos, i understand what particle system, trailrenderer, etc. are used for. but i think for independent guide-videos, using gameobject-examples would be easier to unterstand and copy. (Atleast for me, i do this series with gameobject-bullets and it was confusing at first) Anways, keep up the good work, please! :D
@LlamAcademy
@LlamAcademy Жыл бұрын
Thank you for the feedback! I
@RealRushinRussian
@RealRushinRussian Жыл бұрын
Good tutorial, thank you.
@LlamAcademy
@LlamAcademy Жыл бұрын
You’re welcome 🙌!
@vismortis312
@vismortis312 Жыл бұрын
Hello! Can you help me? How i can return bullet to pool correctly if there was no collision? I've tried coroutine but coroutine brokes trail, direction and position of bullet same bullet when getting it from pool. :(
@LlamAcademy
@LlamAcademy Жыл бұрын
Hmm... I would think you just need to execute the same code that executes on collision, just delayed X seconds. That way they are automatically disabled as they go far away. That's not working for you?
@ronigleydsonvilasnovas8067
@ronigleydsonvilasnovas8067 2 жыл бұрын
Like for you, yes youu! thanks for another great video.
@bulupe
@bulupe Жыл бұрын
Thanks!
@LlamAcademy
@LlamAcademy Жыл бұрын
You're welcome, and thank you 💖
@bluzenkk
@bluzenkk Жыл бұрын
so.. should I be using the Object pool api from unity or just impletment the pool system the old fashion way? its like .. every where I go, i've been hearing something like ahh its good that unity have this new feature, and then follow the Big BUT.... and some downside of using it. i'm just so confuse that unity always gives us too many options to do the same thing and just no de facto way of doing things...
@LlamAcademy
@LlamAcademy Жыл бұрын
I’ve personally replaced my own custom pooling systems with the Unity version and have been happy with the replacement
@Hyphen3372
@Hyphen3372 Жыл бұрын
can you help me fix this error i keep getting it wen i press the shoot button Object reference not set to an instance of an object Bullet.Shoot (UnityEngine.Vector3 Position, UnityEngine.Vector3 Direction, System.Single Speed)
@LlamAcademy
@LlamAcademy Жыл бұрын
I need a lot more information than that to help! Any time you are asking for code help you need to provide the full scripts (or at least the relevant sections) and full error
@fast07hzmc401
@fast07hzmc401 2 жыл бұрын
Would be cool if you could like do a video on how to make enemy's block or like reflect bullets
@LlamAcademy
@LlamAcademy 2 жыл бұрын
Cool idea! Let me add it to the list!
@inkofthedragon
@inkofthedragon Жыл бұрын
I got the object pool working but how would I spawn enemies at random positions around the map? Thanks
@LlamAcademy
@LlamAcademy Жыл бұрын
That’s covered in AI Series Part 4 kzbin.info/www/bejne/a6ayYZeOjsd_Y9U
@mod4797
@mod4797 Жыл бұрын
Hi! What if I have more than one type of bullets in the scene and want to use the same pool? Where should I add the logic of changing the bullet type?
@LlamAcademy
@LlamAcademy Жыл бұрын
Usually you have an Object Pool per type. So if you have 2 prefabs for bullets you would have 2 pools. If they are the same prefab but need to be set up differently after they’re spawned, you’d set them up once you retrieved an object from the pool in whatever script you have that “knows” which type of bullet it should be
@aondy
@aondy Жыл бұрын
Hey there! Were you ever able to figure this out? I’m stuck with the same issue on figuring out how to do a weighted spawner with this objectpool!
@pandathebagel8391
@pandathebagel8391 Жыл бұрын
@@aondy Try using the same GameObject with multiple scripts for each type, that assign the sprite and carry out your different behaviors. In the spawn function run your random chances or whatever selection algorithm you use, and then tell your Instance to run different scripts based on what type they are. So if you had, say fire and water bullets, the Spawn Bullet function bulletController would do something like: (pseudocode, not c#) if (random_range(0,1) == 1) { // Instance is the bullet script Instance.spawnFireBullet(); } else { Instance.spawnWaterBullet(); } and then in the bullet script (Instance) // lets say you have a 2d image as your sprite img = gameObject.GetComponent(); public void spawnFireBullet() { // fireImage would be a saved image file img = fireImage; // special fire bullet code } public void spawnWaterBullet() { img = waterImage; //special water bullet code }
@dibaterman
@dibaterman Жыл бұрын
I heard about this but, I'm kind of fond of my pooler, I kind of made it out of desperation a while ago, I couldn't find a pooler I understood how to set up. Basically my pooler uses an event Func, that takes a transform, a component and returns a class PoolItem which contains the gameObject. I don't ever remove the item from the pooler, instead I check if the item is presently active in the heirarchy. If it is then we instantiate a new item otherwise I grab an inactive one and set it to active. Because the pool is very generalized, I set it to hold a ton of stuff. After that I have two types of what I call sub poolers. Basically if the item being pooled is something everyone uses at most one of, then I just cache that item so in the future the cache it what's used for that specific item. After the item served it's purpose it sets itself inactive, but if it's called again from the same cache it becomes active. Similarly, the other way is populating an array of a component type. Say I had a dust particle effect that I'd have roughly 25 of active at once at most. In the class using it I'd make an array to store each reference. Before going to the main pool it looks to the array from the Dust Particles, otherwise it will check the Pool and add the new items reference to the sub pool. With that method I use GetComponent the first time, but after that it's just cycling through. Also every PoolItem gets it's own uinque ID as well as an owner type. So the pooler will prioritize things with owners that no longer exist in scene then things that are inactive, then instantiating a new item.
@LlamAcademy
@LlamAcademy Жыл бұрын
Thanks for sharing how your system works!
@sumnererhard8865
@sumnererhard8865 2 жыл бұрын
Do you know how you would use the new Object Pooling system in Unity with your Round Based Spawning and Scaling Enemies video?
@LlamAcademy
@LlamAcademy 2 жыл бұрын
Of course. It’s just replacing the custom object pool classes and using this API. On that video we used a custom object pool to manage the enemies, so anywhere those classes are used you’d apply the concepts you learned here in place of them.
@sumnererhard8865
@sumnererhard8865 2 жыл бұрын
@@LlamAcademy Thanks for the reply! In the Round Based Spawning video you were adding a pool from a list of different enemy types and then passing the index to the Instantiate method in the awake function. How would I rewrite that using the new API? I tried using the DictionaryPool method provided in the API but the documentation is so sparse that I can't get it to work. Any chance you know how to populate a pool based on a list of objects using the new API?
@LlamAcademy
@LlamAcademy 2 жыл бұрын
@@sumnererhard8865 much the same way actually. I would keep the normal Dictionary and give it a type of int, ObjectPool. Then we can repeat the same process of creating new ObjectPools for each enemy type and adding them to the Dictionary by index like we did in that video. Instead of doing ObjectPool.CreateInstance, you’d just do new ObjectPool and provide whichever callback functions you need
@midniteoilsoftware
@midniteoilsoftware Жыл бұрын
@@LlamAcademy how would you use this with prefabs where the prefab is just specified via a serializedfield as a GameObject?
@LlamAcademy
@LlamAcademy Жыл бұрын
@@midniteoilsoftware It should be the same, but I’ve never used just GameObject prefabs. For whatever “Manager” you have that’s spawning the objects you just have an ObjectPool to create those prefabs of the generic GameObject type. You wouldn’t be able to use a Dictionary of object pools like I said above, but there’s nothing to stop you from having an ObjectPool that gets GameObjects
@NLPIsrael
@NLPIsrael Жыл бұрын
cant read the texts in the video - is it my problem or int not in focus? how can i solve it pleae?
@NLPIsrael
@NLPIsrael Жыл бұрын
found it. you tube was set to low resultion...
@LlamAcademy
@LlamAcademy Жыл бұрын
Glad you found it!
@while.coyote
@while.coyote 8 ай бұрын
If you haven't yet, you might want to redo the enemy objectpool in your AI series to use this. people might appreciate a more complex usage.
@LlamAcademy
@LlamAcademy 8 ай бұрын
I think in every video after this one I stopped using my own custom pooling solution and started using this one
@gambit7801
@gambit7801 Жыл бұрын
Im having an issue where when an object gets released from the pool it sets active objects to -1 instead of zero. it could be trying to disable 2 at once somehow but then when I spawn many thigns quickly it goes to a very large negative number like -68
@LlamAcademy
@LlamAcademy Жыл бұрын
Sounds like maybe your code is slightly off what we did here or it's duplicating calls to set inactive. Hard to say exactly without seeing that code, but either check out the code from GitHub or compare what you have implemented to what you see in this video and make sure there's no variations!
@gambit7801
@gambit7801 Жыл бұрын
@@LlamAcademy Thank you for the response, I discovered the code was fine but I had bullets start a function from OnEnabled then invoke the ReturnToPool function. Turns out theres a bug with OnEnabled getting called twice and ended up creating a negative pool amount. All fixed now :)
@LlamAcademy
@LlamAcademy Жыл бұрын
Interesting. Thanks for sharing the solution!
@user-mh3or3qs1y
@user-mh3or3qs1y Жыл бұрын
Is there a way to pre-instantiate objects? I've tried to solve this problem, but nothing I tried worked.
@LlamAcademy
@LlamAcademy Жыл бұрын
To pre-instantiate you can just get() a bunch of objects on start or awake and release them immediately
@user-mh3or3qs1y
@user-mh3or3qs1y Жыл бұрын
@@LlamAcademy somehow I forgot to thank you for the answer. Everything worked just fine and I was able to release my first game with object pooling and hookers. Thanks a lot!
@Gatitasecsii
@Gatitasecsii Жыл бұрын
It doesn't work. I mean, maybe it does for this meaningless application, but nothing even appears when I tried this method... it just keeps telling me the object I'm trying to instantiate is null, and that's true, because it is never creating the prefabs.
@LlamAcademy
@LlamAcademy Жыл бұрын
That sounds like maybe you didn’t assign the prefab to instantiate in the inspector
@Mr.SpiderMan1000
@Mr.SpiderMan1000 2 жыл бұрын
UsingUnityEngine.Pool giving error
@LlamAcademy
@LlamAcademy 2 жыл бұрын
Most likely you are not using Unity 2021 LTS or higher if that’s giving you an error
🍟Best French Fries Homemade #cooking #shorts
00:42
BANKII
Рет қаралды 39 МЛН
КАК СПРЯТАТЬ КОНФЕТЫ
00:59
123 GO! Shorts Russian
Рет қаралды 3,1 МЛН
Sprinting with More and More Money
00:29
MrBeast
Рет қаралды 118 МЛН
Object Pooling in Unity 2021 is Dope AF
18:10
Tarodev
Рет қаралды 118 М.
OBJECT POOLING in Unity
17:23
Brackeys
Рет қаралды 427 М.
Top 5 Optimization Tips from Building a Mobile Game in Unity
15:54
The Power of Scriptable Objects as Middle-Men
17:41
samyam
Рет қаралды 116 М.
Unity Performance Tips: Draw Calls
4:24
Lofi Dev
Рет қаралды 177 М.
How to Setup An Object Pool (New Built In Method) | Unity Tutorial
29:21
Sasquatch B Studios
Рет қаралды 10 М.
How to Program in Unity: Command Pattern Explained
22:37
iHeartGameDev
Рет қаралды 64 М.
Rethink Everything with Scriptable Object VARIABLES
15:28
🍟Best French Fries Homemade #cooking #shorts
00:42
BANKII
Рет қаралды 39 МЛН