Home > OS >  How to access the object you instantiated or set a limit for spawnable objects unity 3d
How to access the object you instantiated or set a limit for spawnable objects unity 3d

Time:06-20

Im stuck in a problem that I have, I made a script that makes objects, simple script no addons. But I want to set a limit on how much enemies there can be at once (because its laggy) I have absolutely no idea how, any help appreciated, Thanks!

CodePudding user response:

One relatively simple approach is to create a manager script that handles the spawning. It can internally track the number of spawned objects and then just not spawn the objects once the maximum number has been reached.

This sounds like you might want an object pool, which is built into Unity 2021 (https://docs.unity3d.com/2021.1/Documentation/ScriptReference/Pool.ObjectPool_1.html).

CodePudding user response:

There's bunch of ways to do that, but the most simple one is to declare a GameObject\Transform\your enherit from monobehavior collection in that script:

private List<GameObject> _entities;

And then you add it from Instantiate method, like this:

_entities.Add(Instantiate(*your prefab and other parameters*));

Instantiate() method returns you instatiated GameObject

and setting the limit here should be fairly easy as well:

 if (_entities.Count < _entitiesLimit)
 {
      _entities.Add(Instatiate(_prefab));
 }
  • Related