Using an object pool instead

I figured that since I was doing the design patterns course at the same time and wanted to use object pooling in a real scenario this would be a perfect time. It actually works quite well, with the health getting a DamageText from the pool every time it takes damage. The DamageText then returns itself to the pool after fading out.

public class DamageTextScript : MonoBehaviour
{
    private DamageTextPool pool;
    private float secondsAlive = 0;
    
    public void SetPool(DamageTextPool pool)
    {
        this.pool = pool;
    }

    private void OnEnable()
    {
        GetComponent<RectTransform>().rotation = Camera.main.transform.rotation;
        GetComponent<TextMeshPro>().alpha = 1f;
        secondsAlive = 0;
    }

    private void Update()
    {
        if (secondsAlive < 1.5f)
        {
            secondsAlive += Time.deltaTime;
            GetComponent<TextMeshPro>().alpha -= 0.03f;
            transform.position += Vector3.up * 0.03f;
        }
        else
        {
            pool.damageTextPool.Release(this);
        }
    }

    public void SetPosition(Vector3 position)
    {
        position += Vector3.up * 1; // to put us above the head
        transform.position = position;
    }

    public void SetDamage(int damage) => GetComponent<TextMeshPro>().text = damage.ToString();
}

I just watched the next four videos and realized that he explained everything there. Oops. I keep getting ahead of myself and brainstorming then realizing he did that for me.

Privacy & Terms