Recap: Bullet Pool
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 40 of 50.
Challenge
MediumTarget practice. The arrows slide the Tank left and right (ready), and the two red targets have a Target script with Hit() (ready). Make the tank fire pooled bullets:
- In
Tank.cs, keep anObjectPool<Bullet>that makes bullets frombulletPrefab, switches them on when taken out and off when they come back, destroys those it lets go, and keeps at most 4 spare bullets. - Space takes a bullet from the pool and starts it 1 unit in front of the tank.
- In
Bullet.cs, a bullet flies forward (+z) atspeed(15). When it hits something with a Target script (the bullet's collider is a trigger), it calls the target'sHit()and goes back to the pool at once. A bullet that hits nothing goes back afterlife(1) seconds. - Every shot gets a bullet's full life, a reused one too, and a bullet goes back to the pool once per shot.
Press Play, shoot both targets, then Check.
Try it yourself
using UnityEngine;
using UnityEngine.Pool;
public class Bullet : MonoBehaviour
{
public float speed = 15f;
public float life = 1f;
// Fly forward; go back to the pool when it hits a Target, or after life seconds
}
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types