Home > other >  Object pooling
Object pooling

Time:09-30

Create a bullet object using coroutines pool

CodePudding user response:

Object pooling is not the case?
 internal sealed class ObjectPool 
{
List pool;
Int maxCount;
Int a boundary.
Internal ObjectPool (int Max)
{
The pool=new List (Max);
MaxCount=Max;
A boundary=0;
}

Internal bool Add value (T)
{
if (value !=null & amp; & Pool. Count & lt; MaxCount)
{
The pool. The Add (value);
Boundary++;
return true;
}
return false;
}

Internal T Pop ()
{
The lock (pool)
{
If (a boundary & gt; 0)
{
- a boundary;
Return the pool/boundary;
}
The else
{
Return the default (T);
}
}
}

Internal void Push value (T)
{
if (value !=null)
{
The lock (pool)
{
Int index=pool. IndexOf (value, a boundary);
if (index !=a boundary)
{
The pool [index]=pool [boundary];
The pool [boundary]=value;
}
Boundary++;
}
}
}
}


 public class Bullet: MonoBehaviour 
{
The static ObjectPool CartridgePool;

Public static void InitPool (int Max)
{
CartridgePool=new ObjectPool (Max);
For (int I=0; i {
CartridgePool. Add (Resources. Load (" cartridge "));
}
}

Public static void Launch (Transform the current, the Transform target)
{
Var car=cartridgePool. Pop ();
If (car!=null)
{
The car. The transform. The position=current. The position;
The car. The transform. LookAt (target);
The car. The gameObject. SetActive (true);
}
}

Private void OnEnable ()
{
StartCoroutine (Timeout ());
}

IEnumerator Timeout ()
{
Yield return new WaitForSeconds (5);
GameObject. SetActive (false);
CartridgePool. Push (this);
}
}


 public class Test: MonoBehaviour 
{
The Transform mouseTarget;

Private void the Start ()
{
Bullet. InitPool (100);
}
Private void the Update ()
{
If (Input. GetMouseButtonDown (0))
{
Bullet. Launch (transform, mouseTarget);
}
}
}
  • Related