How can i optimize hundreds of objects firing at each other? I’ve already got box colliders because they are the least memory usage by a long shot. everything is fine until i add this part:
void OnTriggerStay(Collider other)
{
if (other.tag == "Enemy" )
{
if (inTrigger && Time.time > lastFireTime)
{
lastFireTime = Time.time + delayTime;
Fire(other.transform);
}
}
else
Physics.IgnoreCollision(collider, other.collider);
}
void Fire(Transform currentTarget)
{
GameObject shot = Instantiate(bullet, transform.position, Quaternion.identity) as GameObject;
shot.GetComponent<BulletPhysics>().target = currentTarget;
Destroy((shot.gameObject), 2);
}
basically i think the slowdown is coming from the way i’m doing my delay is there a better way? The profiler states 80k calls is being done in stay in a matter of seconds
Two things to keep in mind:
-
Make sure that all your bullets are using only 1 Draw Call. Read about dynamic batching on Unity.
-
Use Object Pooling. Search a bit about how to implement it, but the basic idea is to keep a Queue of the object you will be “creating” a lot (bullets). Instead of intantiate every single one (instantiate is slow), deactivate objects that you are no longer using and re-use them again when you need a new instance. For example:
using System.Collections.Generic;
//Pool
private Queue<BulletPhysics> bulletPool = new Queue<BulletPhysics>();
public BulletPhysics GetBulletFromPool()
{
BulletPhysics bullet = null;
if (this.bulletPool .Count == 0)
{
bullet = Instantiate(this.bulletPrefab) as BulletPhysics;
}
else
{
bullet = this.bulletPool .Dequeue();
}
bullet.gameObject.SetActive(true);
bullet.Init();
return bullet;
}
public void ReturnBulletToPool(BulletPhysics bullet)
{
bullet.ClearData();
this.bulletPool.Enqueue(bullet);
}