Files
AppleHillsProduction/Assets/Scripts/Minigames/DivingForPictures/BubblePool.cs
2025-09-16 15:02:57 +02:00

118 lines
3.7 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace Minigames.DivingForPictures
{
/// <summary>
/// Manages a pool of bubble objects to reduce garbage collection overhead.
/// </summary>
public class BubblePool : MonoBehaviour
{
[Tooltip("Initial number of bubbles to pre-instantiate")]
public int initialPoolSize = 10;
[Tooltip("Maximum number of bubbles to keep in the pool")]
public int maxPoolSize = 30;
private Stack<Bubble> pooledBubbles = new Stack<Bubble>();
private Bubble bubblePrefab;
private int totalBubblesCreated = 0;
private int totalBubblesReturned = 0;
/// <summary>
/// Initialize the pool with the bubble prefab
/// </summary>
/// <param name="prefab">The bubble prefab to use</param>
public void Initialize(Bubble prefab)
{
bubblePrefab = prefab;
// Pre-instantiate bubbles
for (int i = 0; i < initialPoolSize; i++)
{
CreateNewBubble();
}
Debug.Log($"BubblePool initialized with {initialPoolSize} bubbles");
}
/// <summary>
/// Creates a new bubble instance and adds it to the pool
/// </summary>
private Bubble CreateNewBubble()
{
if (bubblePrefab == null)
{
Debug.LogError("BubblePool: bubblePrefab is null! Call Initialize first.");
return null;
}
Bubble bubble = Instantiate(bubblePrefab, transform);
bubble.gameObject.SetActive(false);
// Set the pool reference so the bubble knows where to return
bubble.SetPool(this);
pooledBubbles.Push(bubble);
totalBubblesCreated++;
return bubble;
}
/// <summary>
/// Gets a bubble from the pool, or creates a new one if the pool is empty
/// </summary>
/// <returns>A bubble instance ready to use</returns>
public Bubble GetBubble()
{
Bubble bubble;
if (pooledBubbles.Count > 0)
{
bubble = pooledBubbles.Pop();
}
else
{
bubble = CreateNewBubble();
}
// Ensure the bubble has a reference to this pool
bubble.SetPool(this);
bubble.gameObject.SetActive(true);
bubble.ResetState();
return bubble;
}
/// <summary>
/// Returns a bubble to the pool
/// </summary>
/// <param name="bubble">The bubble to return to the pool</param>
public void ReturnBubble(Bubble bubble)
{
if (bubble == null) return;
// Only add to pool if we're under the maximum size
if (pooledBubbles.Count < maxPoolSize)
{
// Deactivate and reparent
bubble.gameObject.SetActive(false);
bubble.transform.SetParent(transform);
// Add to pool
pooledBubbles.Push(bubble);
totalBubblesReturned++;
}
else
{
Destroy(bubble.gameObject);
}
}
/// <summary>
/// Logs pool statistics
/// </summary>
public void LogPoolStats()
{
Debug.Log($"[BubblePool] Pooled bubbles: {pooledBubbles.Count}/{maxPoolSize} (Created: {totalBubblesCreated}, Returned: {totalBubblesReturned})");
}
}
}