Working single-purpose object pooling solution
This commit is contained in:
@@ -10,39 +10,83 @@ namespace Minigames.DivingForPictures
|
||||
public float speed = 1f;
|
||||
public float wobbleSpeed = 1f;
|
||||
private SpriteRenderer spriteRenderer;
|
||||
private SpriteRenderer bottleSpriteRenderer;
|
||||
private SpriteRenderer bubbleSpriteRenderer; // Renamed from bottleSpriteRenderer
|
||||
private float timeOffset;
|
||||
private float minScale = 0.2f;
|
||||
private float maxScale = 1.2f;
|
||||
private float baseScale = 1f; // Added to store the initial scale
|
||||
|
||||
private Camera mainCamera; // Cache camera reference
|
||||
private BubblePool parentPool; // Reference to the pool this bubble came from
|
||||
|
||||
void Awake()
|
||||
{
|
||||
// Cache references and randomize time offset for wobble
|
||||
spriteRenderer = GetComponent<SpriteRenderer>();
|
||||
timeOffset = Random.value * 100f;
|
||||
// Find the child named "BottleSprite" and get its SpriteRenderer
|
||||
Transform bottleSpriteTransform = transform.Find("BubbleSprite");
|
||||
if (bottleSpriteTransform != null)
|
||||
// Find the child named "BubbleSprite" and get its SpriteRenderer
|
||||
Transform bubbleSpriteTransform = transform.Find("BubbleSprite");
|
||||
if (bubbleSpriteTransform != null)
|
||||
{
|
||||
bottleSpriteRenderer = bottleSpriteTransform.GetComponent<SpriteRenderer>();
|
||||
bubbleSpriteRenderer = bubbleSpriteTransform.GetComponent<SpriteRenderer>();
|
||||
}
|
||||
|
||||
// Cache camera reference
|
||||
mainCamera = Camera.main;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// Move bubble upward
|
||||
transform.position += Vector3.up * speed * Time.deltaTime;
|
||||
transform.position += Vector3.up * (speed * Time.deltaTime);
|
||||
|
||||
// Wobble effect (smooth oscillation between min and max scale)
|
||||
float t = (Mathf.Sin((Time.time + timeOffset) * wobbleSpeed) + 1f) * 0.5f; // t in [0,1]
|
||||
float newScale = Mathf.Lerp(minScale, maxScale, t);
|
||||
transform.localScale = Vector3.one * newScale;
|
||||
// Destroy when off screen
|
||||
if (transform.position.y > Camera.main.orthographicSize + 2f)
|
||||
float wobbleFactor = Mathf.Lerp(minScale, maxScale, t);
|
||||
transform.localScale = Vector3.one * (baseScale * wobbleFactor);
|
||||
|
||||
// Destroy when off screen - using cached camera reference
|
||||
if (mainCamera != null && transform.position.y > mainCamera.orthographicSize + 2f)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
OnBubbleDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when bubble is about to be destroyed
|
||||
/// </summary>
|
||||
private void OnBubbleDestroy()
|
||||
{
|
||||
// Use the cached pool reference instead of finding it each time
|
||||
if (parentPool != null)
|
||||
{
|
||||
parentPool.ReturnBubble(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback to find the pool if the reference is somehow lost
|
||||
BubblePool pool = FindFirstObjectByType<BubblePool>();
|
||||
if (pool != null)
|
||||
{
|
||||
Debug.LogWarning("Bubble is missing its parent pool reference, finding pool as fallback");
|
||||
pool.ReturnBubble(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the parent pool for this bubble
|
||||
/// </summary>
|
||||
/// <param name="pool">The bubble pool that created this bubble</param>
|
||||
public void SetPool(BubblePool pool)
|
||||
{
|
||||
parentPool = pool;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the main sprite for the bubble.
|
||||
/// </summary>
|
||||
@@ -54,13 +98,22 @@ namespace Minigames.DivingForPictures
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the sprite for the child "BottleSprite" renderer.
|
||||
/// Sets the sprite for the child "BubbleSprite" renderer.
|
||||
/// </summary>
|
||||
/// <param name="sprite">Sprite to assign.</param>
|
||||
public void SetBottleSprite(Sprite sprite)
|
||||
public void SetBubbleSprite(Sprite sprite)
|
||||
{
|
||||
if (bottleSpriteRenderer != null)
|
||||
bottleSpriteRenderer.sprite = sprite;
|
||||
if (bubbleSpriteRenderer != null)
|
||||
bubbleSpriteRenderer.sprite = sprite;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the base scale for the bubble
|
||||
/// </summary>
|
||||
/// <param name="scale">Base scale value</param>
|
||||
public void SetBaseScale(float scale)
|
||||
{
|
||||
baseScale = scale;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -73,5 +126,13 @@ namespace Minigames.DivingForPictures
|
||||
minScale = min;
|
||||
maxScale = max;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the bubble state for reuse from object pool
|
||||
/// </summary>
|
||||
public void ResetState()
|
||||
{
|
||||
timeOffset = Random.value * 100f;
|
||||
}
|
||||
}
|
||||
}
|
||||
117
Assets/Scripts/Minigames/DivingForPictures/BubblePool.cs
Normal file
117
Assets/Scripts/Minigames/DivingForPictures/BubblePool.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
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})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 45cdaed0c047423bbb0b7380cd3687f3
|
||||
timeCreated: 1758015081
|
||||
@@ -19,9 +19,32 @@ namespace Minigames.DivingForPictures
|
||||
public float spawnY = -5f;
|
||||
public float wobbleMinScale = 0.2f;
|
||||
public float wobbleMaxScale = 1.2f;
|
||||
|
||||
[Header("Object Pooling")]
|
||||
public bool useObjectPooling = true;
|
||||
public int initialPoolSize = 10;
|
||||
public int maxPoolSize = 30;
|
||||
|
||||
private float _timer;
|
||||
private float _nextSpawnInterval;
|
||||
private BubblePool _bubblePool;
|
||||
private Camera _mainCamera; // Cache camera reference
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_mainCamera = Camera.main;
|
||||
|
||||
if (useObjectPooling)
|
||||
{
|
||||
// Create the bubble pool
|
||||
GameObject poolGO = new GameObject("BubblePool");
|
||||
poolGO.transform.SetParent(transform);
|
||||
_bubblePool = poolGO.AddComponent<BubblePool>();
|
||||
_bubblePool.initialPoolSize = initialPoolSize;
|
||||
_bubblePool.maxPoolSize = maxPoolSize;
|
||||
_bubblePool.Initialize(bubblePrefab);
|
||||
}
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
@@ -56,21 +79,36 @@ namespace Minigames.DivingForPictures
|
||||
{
|
||||
float x = Random.Range(spawnXMin, spawnXMax);
|
||||
Vector3 spawnPos = new Vector3(x, spawnY, 0f);
|
||||
Bubble bubble = Instantiate(bubblePrefab, spawnPos, Quaternion.identity, transform);
|
||||
|
||||
Bubble bubble;
|
||||
if (useObjectPooling && _bubblePool != null)
|
||||
{
|
||||
bubble = _bubblePool.GetBubble();
|
||||
bubble.transform.position = spawnPos;
|
||||
}
|
||||
else
|
||||
{
|
||||
bubble = Instantiate(bubblePrefab, spawnPos, Quaternion.identity, transform);
|
||||
}
|
||||
|
||||
// Randomize bubble properties
|
||||
bubble.speed = Random.Range(speedRange.x, speedRange.y);
|
||||
bubble.wobbleSpeed = Random.Range(wobbleSpeedRange.x, wobbleSpeedRange.y);
|
||||
float scale = Random.Range(scaleRange.x, scaleRange.y);
|
||||
bubble.transform.localScale = Vector3.one * scale;
|
||||
// Assign random sprite to BottleSprite
|
||||
|
||||
// Set base scale (initial size) for the bubble
|
||||
float baseScale = Random.Range(scaleRange.x, scaleRange.y);
|
||||
bubble.SetBaseScale(baseScale);
|
||||
|
||||
// Assign random sprite to BubbleSprite (fixed naming from BottleSprite)
|
||||
if (bubbleSprites != null && bubbleSprites.Length > 0)
|
||||
{
|
||||
Sprite randomSprite = bubbleSprites[Random.Range(0, bubbleSprites.Length)];
|
||||
bubble.SetBottleSprite(randomSprite);
|
||||
bubble.SetBubbleSprite(randomSprite);
|
||||
}
|
||||
|
||||
// Random rotation
|
||||
bubble.transform.rotation = Quaternion.Euler(0f, 0f, Random.Range(0f, 360f));
|
||||
|
||||
// Pass min/max scale for wobble clamping
|
||||
bubble.SetWobbleScaleLimits(wobbleMinScale, wobbleMaxScale);
|
||||
}
|
||||
|
||||
244
Assets/Scripts/Minigames/DivingForPictures/TrenchTilePool.cs
Normal file
244
Assets/Scripts/Minigames/DivingForPictures/TrenchTilePool.cs
Normal file
@@ -0,0 +1,244 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Minigames.DivingForPictures
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages a pool of trench tile objects to reduce garbage collection overhead.
|
||||
/// Optimized for handling a large number of different prefab types.
|
||||
/// </summary>
|
||||
public class TrenchTilePool : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Whether to pre-instantiate tiles during initialization or create them on demand")]
|
||||
public bool preInstantiateTiles = false;
|
||||
|
||||
[Tooltip("Initial number of tiles to pre-instantiate per prefab (if preInstantiateTiles is true)")]
|
||||
public int initialTilesPerPrefab = 2;
|
||||
|
||||
[Tooltip("Maximum number of tiles to keep in the pool across all prefab types")]
|
||||
public int totalMaxPoolSize = 50;
|
||||
|
||||
[Tooltip("Maximum number of inactive instances to keep per prefab type")]
|
||||
public int maxPerPrefabPoolSize = 5;
|
||||
|
||||
[Tooltip("Maximum number of tiles to keep in the pool (legacy, use maxPerPrefabPoolSize instead)")]
|
||||
public int maxPoolSize = 5;
|
||||
|
||||
private Dictionary<int, Stack<GameObject>> pooledTiles = new Dictionary<int, Stack<GameObject>>();
|
||||
private Dictionary<int, int> prefabUsageCount = new Dictionary<int, int>();
|
||||
private List<GameObject> tilePrefabs;
|
||||
private int totalPooledCount = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the pool with the tile prefabs
|
||||
/// </summary>
|
||||
/// <param name="prefabs">List of tile prefabs to use</param>
|
||||
public void Initialize(List<GameObject> prefabs)
|
||||
{
|
||||
tilePrefabs = prefabs;
|
||||
|
||||
// Initialize usage tracking
|
||||
for (int i = 0; i < prefabs.Count; i++)
|
||||
{
|
||||
prefabUsageCount[i] = 0;
|
||||
pooledTiles[i] = new Stack<GameObject>();
|
||||
}
|
||||
|
||||
// Pre-instantiate tiles only if enabled
|
||||
if (preInstantiateTiles)
|
||||
{
|
||||
// Calculate how many to pre-instantiate based on available pool size
|
||||
int totalToCreate = Mathf.Min(totalMaxPoolSize, prefabs.Count * initialTilesPerPrefab);
|
||||
int perPrefab = Mathf.Max(1, totalToCreate / prefabs.Count);
|
||||
|
||||
for (int i = 0; i < prefabs.Count; i++)
|
||||
{
|
||||
for (int j = 0; j < perPrefab; j++)
|
||||
{
|
||||
if (totalPooledCount >= totalMaxPoolSize) break;
|
||||
CreateNewTile(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new tile instance and adds it to the pool
|
||||
/// </summary>
|
||||
private GameObject CreateNewTile(int prefabIndex)
|
||||
{
|
||||
if (tilePrefabs == null || prefabIndex >= tilePrefabs.Count)
|
||||
{
|
||||
Debug.LogError("TrenchTilePool: Invalid prefab index or tilePrefabs is null!");
|
||||
return null;
|
||||
}
|
||||
|
||||
GameObject prefab = tilePrefabs[prefabIndex];
|
||||
GameObject tile = Instantiate(prefab, transform);
|
||||
tile.SetActive(false);
|
||||
|
||||
if (!pooledTiles.ContainsKey(prefabIndex))
|
||||
{
|
||||
pooledTiles[prefabIndex] = new Stack<GameObject>();
|
||||
}
|
||||
|
||||
pooledTiles[prefabIndex].Push(tile);
|
||||
totalPooledCount++;
|
||||
return tile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a tile from the pool, or creates a new one if the pool is empty
|
||||
/// </summary>
|
||||
/// <returns>A tile instance ready to use</returns>
|
||||
public GameObject GetTile(int prefabIndex)
|
||||
{
|
||||
GameObject tile;
|
||||
|
||||
// Track usage frequency
|
||||
if (prefabUsageCount.ContainsKey(prefabIndex))
|
||||
{
|
||||
prefabUsageCount[prefabIndex]++;
|
||||
}
|
||||
else
|
||||
{
|
||||
prefabUsageCount[prefabIndex] = 1;
|
||||
}
|
||||
|
||||
if (pooledTiles.ContainsKey(prefabIndex) && pooledTiles[prefabIndex].Count > 0)
|
||||
{
|
||||
tile = pooledTiles[prefabIndex].Pop();
|
||||
totalPooledCount--;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create new tile without adding to pool
|
||||
GameObject prefab = tilePrefabs[prefabIndex];
|
||||
tile = Instantiate(prefab, transform);
|
||||
}
|
||||
|
||||
tile.SetActive(true);
|
||||
return tile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a tile to the pool
|
||||
/// </summary>
|
||||
/// <param name="tile">The tile to return to the pool</param>
|
||||
/// <param name="prefabIndex">The index of the prefab this tile was created from</param>
|
||||
public void ReturnTile(GameObject tile, int prefabIndex)
|
||||
{
|
||||
if (tile == null) return;
|
||||
|
||||
// Check if we're under the maximum pool size for this prefab type
|
||||
bool keepTile = totalPooledCount < totalMaxPoolSize;
|
||||
|
||||
// Additional constraint: don't keep too many of any single prefab type
|
||||
if (pooledTiles.ContainsKey(prefabIndex) &&
|
||||
pooledTiles[prefabIndex].Count >= maxPerPrefabPoolSize)
|
||||
{
|
||||
keepTile = false;
|
||||
}
|
||||
|
||||
if (keepTile)
|
||||
{
|
||||
tile.SetActive(false);
|
||||
tile.transform.SetParent(transform);
|
||||
|
||||
if (!pooledTiles.ContainsKey(prefabIndex))
|
||||
{
|
||||
pooledTiles[prefabIndex] = new Stack<GameObject>();
|
||||
}
|
||||
|
||||
pooledTiles[prefabIndex].Push(tile);
|
||||
totalPooledCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(tile);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trims the pool to remove excess objects
|
||||
/// Can be called periodically or when memory pressure is high
|
||||
/// </summary>
|
||||
public void TrimExcess()
|
||||
{
|
||||
// If we're under the limit, no need to trim
|
||||
if (totalPooledCount <= totalMaxPoolSize) return;
|
||||
|
||||
// Calculate how many to remove
|
||||
int excessCount = totalPooledCount - totalMaxPoolSize;
|
||||
|
||||
// Get prefab indices sorted by usage (least used first)
|
||||
List<KeyValuePair<int, int>> sortedUsage = new List<KeyValuePair<int, int>>(prefabUsageCount);
|
||||
sortedUsage.Sort((a, b) => a.Value.CompareTo(b.Value));
|
||||
|
||||
// Remove tiles from least used prefabs first
|
||||
foreach (var usage in sortedUsage)
|
||||
{
|
||||
int prefabIndex = usage.Key;
|
||||
if (!pooledTiles.ContainsKey(prefabIndex) || pooledTiles[prefabIndex].Count == 0) continue;
|
||||
|
||||
// How many to remove from this prefab type
|
||||
int toRemove = Mathf.Min(pooledTiles[prefabIndex].Count, excessCount);
|
||||
|
||||
for (int i = 0; i < toRemove; i++)
|
||||
{
|
||||
if (pooledTiles[prefabIndex].Count == 0) break;
|
||||
|
||||
GameObject tile = pooledTiles[prefabIndex].Pop();
|
||||
Destroy(tile);
|
||||
totalPooledCount--;
|
||||
excessCount--;
|
||||
|
||||
if (excessCount <= 0) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs pool statistics to the console
|
||||
/// </summary>
|
||||
public void LogPoolStats()
|
||||
{
|
||||
Debug.Log($"[TrenchTilePool] Total pooled objects: {totalPooledCount}/{totalMaxPoolSize}");
|
||||
|
||||
string prefabDetails = "";
|
||||
int index = 0;
|
||||
foreach (var entry in pooledTiles)
|
||||
{
|
||||
int prefabIndex = entry.Key;
|
||||
int count = entry.Value.Count;
|
||||
int usageCount = prefabUsageCount.ContainsKey(prefabIndex) ? prefabUsageCount[prefabIndex] : 0;
|
||||
|
||||
string prefabName = prefabIndex < tilePrefabs.Count ? tilePrefabs[prefabIndex].name : "Unknown";
|
||||
prefabDetails += $"\n - {prefabName}: {count} pooled, {usageCount} usages";
|
||||
|
||||
// Limit the output to avoid too much text
|
||||
if (++index >= 10 && pooledTiles.Count > 10)
|
||||
{
|
||||
prefabDetails += $"\n - ...and {pooledTiles.Count - 10} more prefab types";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Debug.Log($"[TrenchTilePool] Pool details:{prefabDetails}");
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private float _lastLogTime = 0f;
|
||||
|
||||
void Update()
|
||||
{
|
||||
// Log pool stats every 5 seconds if in the editor
|
||||
if (Time.time - _lastLogTime > 5f)
|
||||
{
|
||||
LogPoolStats();
|
||||
_lastLogTime = Time.time;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fc32ce01955e4e44b4c1d28871d64049
|
||||
timeCreated: 1758015121
|
||||
@@ -15,7 +15,7 @@ namespace Minigames.DivingForPictures
|
||||
public List<GameObject> tilePrefabs;
|
||||
|
||||
[Header("Tile Settings")]
|
||||
private const float TileHeight = 5f; // Set to match prefab height
|
||||
private Dictionary<GameObject, float> _tileHeights = new Dictionary<GameObject, float>();
|
||||
public int initialTileCount = 3;
|
||||
public float tileSpawnBuffer = 1f;
|
||||
|
||||
@@ -23,6 +23,14 @@ namespace Minigames.DivingForPictures
|
||||
public float moveSpeed = 3f;
|
||||
public float speedUpFactor = 0.2f;
|
||||
public float speedUpInterval = 10f;
|
||||
public float maxMoveSpeed = 12f; // Added a cap to the movement speed
|
||||
|
||||
[Header("Object Pooling")]
|
||||
public bool useObjectPooling = true;
|
||||
public bool preInstantiateTiles = false; // Added option to control pre-instantiation
|
||||
public int initialTilesPerPrefab = 2;
|
||||
public int maxPerPrefabPoolSize = 2;
|
||||
public int totalMaxPoolSize = 10; // Total pool size across all prefab types
|
||||
|
||||
[FormerlySerializedAs("OnTileSpawned")] [Header("Events")]
|
||||
public UnityEvent<GameObject> onTileSpawned;
|
||||
@@ -37,14 +45,61 @@ namespace Minigames.DivingForPictures
|
||||
private Camera _mainCamera;
|
||||
private float _screenBottom;
|
||||
private float _screenTop;
|
||||
private TrenchTilePool _tilePool;
|
||||
|
||||
private const float TileSpawnZ = -1f; // All spawned tiles should have z = -1
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_mainCamera = Camera.main;
|
||||
|
||||
// Calculate tile heights for each prefab
|
||||
foreach (var prefab in tilePrefabs)
|
||||
{
|
||||
Renderer renderer = prefab.GetComponentInChildren<Renderer>();
|
||||
if (renderer != null)
|
||||
{
|
||||
_tileHeights[prefab] = renderer.bounds.size.y;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback in case no renderer is found
|
||||
_tileHeights[prefab] = 5f;
|
||||
Debug.LogWarning($"No renderer found in prefab {prefab.name}. Using default height of 5.");
|
||||
}
|
||||
}
|
||||
|
||||
if (useObjectPooling)
|
||||
{
|
||||
// Create the tile pool
|
||||
GameObject poolGO = new GameObject("TrenchTilePool");
|
||||
poolGO.transform.SetParent(transform);
|
||||
_tilePool = poolGO.AddComponent<TrenchTilePool>();
|
||||
_tilePool.preInstantiateTiles = preInstantiateTiles;
|
||||
_tilePool.initialTilesPerPrefab = initialTilesPerPrefab;
|
||||
_tilePool.maxPerPrefabPoolSize = maxPerPrefabPoolSize;
|
||||
_tilePool.totalMaxPoolSize = totalMaxPoolSize;
|
||||
_tilePool.Initialize(tilePrefabs);
|
||||
|
||||
// Periodically trim the pool to optimize memory usage
|
||||
InvokeRepeating(nameof(TrimExcessPooledTiles), 10f, 30f);
|
||||
}
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
_mainCamera = Camera.main;
|
||||
CalculateScreenBounds();
|
||||
for (int i = 0; i < initialTileCount; i++)
|
||||
{
|
||||
SpawnTileAtY(_screenBottom + i * TileHeight);
|
||||
float y = _screenBottom;
|
||||
// Calculate proper Y position based on previous tiles
|
||||
if (i > 0 && _activeTiles.Count > 0)
|
||||
{
|
||||
GameObject prevTile = _activeTiles[_activeTiles.Count - 1];
|
||||
float prevHeight = GetTileHeight(prevTile);
|
||||
y = prevTile.transform.position.y - prevHeight;
|
||||
}
|
||||
SpawnTileAtY(y);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,11 +135,29 @@ namespace Minigames.DivingForPictures
|
||||
{
|
||||
if (_activeTiles.Count == 0) return;
|
||||
GameObject topTile = _activeTiles[0];
|
||||
if (topTile.transform.position.y - TileHeight / 2 > _screenTop + tileSpawnBuffer)
|
||||
float tileHeight = GetTileHeight(topTile);
|
||||
if (topTile.transform.position.y - tileHeight / 2 > _screenTop + tileSpawnBuffer)
|
||||
{
|
||||
_activeTiles.RemoveAt(0);
|
||||
onTileDestroyed?.Invoke(topTile);
|
||||
Destroy(topTile);
|
||||
|
||||
if (useObjectPooling && _tilePool != null)
|
||||
{
|
||||
// Find the prefab index for this tile
|
||||
int prefabIndex = GetPrefabIndex(topTile);
|
||||
if (prefabIndex >= 0)
|
||||
{
|
||||
_tilePool.ReturnTile(topTile, prefabIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(topTile);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Destroy(topTile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,10 +165,11 @@ namespace Minigames.DivingForPictures
|
||||
{
|
||||
if (_activeTiles.Count == 0) return;
|
||||
GameObject bottomTile = _activeTiles[^1];
|
||||
float bottomEdge = bottomTile.transform.position.y - TileHeight / 2;
|
||||
float tileHeight = GetTileHeight(bottomTile);
|
||||
float bottomEdge = bottomTile.transform.position.y - tileHeight / 2;
|
||||
if (bottomEdge > _screenBottom - tileSpawnBuffer)
|
||||
{
|
||||
float newY = bottomTile.transform.position.y - TileHeight;
|
||||
float newY = bottomTile.transform.position.y - tileHeight;
|
||||
SpawnTileAtY(newY);
|
||||
}
|
||||
}
|
||||
@@ -105,7 +179,7 @@ namespace Minigames.DivingForPictures
|
||||
_speedUpTimer += Time.deltaTime;
|
||||
if (_speedUpTimer >= speedUpInterval)
|
||||
{
|
||||
moveSpeed += speedUpFactor;
|
||||
moveSpeed = Mathf.Min(moveSpeed + speedUpFactor, maxMoveSpeed);
|
||||
_speedUpTimer = 0f;
|
||||
}
|
||||
}
|
||||
@@ -114,8 +188,21 @@ namespace Minigames.DivingForPictures
|
||||
{
|
||||
int prefabIndex = GetWeightedRandomTileIndex();
|
||||
GameObject prefab = tilePrefabs[prefabIndex];
|
||||
// Use the prefab's original rotation
|
||||
GameObject tile = Instantiate(prefab, new Vector3(0f, y, 0f), prefab.transform.rotation, transform);
|
||||
GameObject tile;
|
||||
|
||||
if (useObjectPooling && _tilePool != null)
|
||||
{
|
||||
tile = _tilePool.GetTile(prefabIndex);
|
||||
tile.transform.position = new Vector3(0f, y, TileSpawnZ);
|
||||
tile.transform.rotation = prefab.transform.rotation;
|
||||
tile.transform.SetParent(transform);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Use the prefab's original rotation
|
||||
tile = Instantiate(prefab, new Vector3(0f, y, TileSpawnZ), prefab.transform.rotation, transform);
|
||||
}
|
||||
|
||||
_activeTiles.Add(tile);
|
||||
_tileLastUsed[prefabIndex] = _spawnCounter++;
|
||||
onTileSpawned?.Invoke(tile);
|
||||
@@ -143,6 +230,65 @@ namespace Minigames.DivingForPictures
|
||||
}
|
||||
return Random.Range(0, n); // fallback
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the height of a tile based on its prefab or renderer bounds
|
||||
/// </summary>
|
||||
/// <param name="tile">The tile to measure</param>
|
||||
/// <returns>The height of the tile</returns>
|
||||
private float GetTileHeight(GameObject tile)
|
||||
{
|
||||
// Check if this is a known prefab
|
||||
foreach (var prefab in tilePrefabs)
|
||||
{
|
||||
// Check if this tile was created from this prefab
|
||||
if (tile.name.StartsWith(prefab.name))
|
||||
{
|
||||
if (_tileHeights.TryGetValue(prefab, out float height))
|
||||
{
|
||||
return height;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If not found, calculate it from the renderer
|
||||
Renderer renderer = tile.GetComponentInChildren<Renderer>();
|
||||
if (renderer != null)
|
||||
{
|
||||
return renderer.bounds.size.y;
|
||||
}
|
||||
|
||||
// Fallback
|
||||
return 5f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the index of the prefab that was used to create this tile
|
||||
/// </summary>
|
||||
/// <param name="tile">The tile to check</param>
|
||||
/// <returns>The index of the prefab or -1 if not found</returns>
|
||||
private int GetPrefabIndex(GameObject tile)
|
||||
{
|
||||
for (int i = 0; i < tilePrefabs.Count; i++)
|
||||
{
|
||||
if (tile.name.StartsWith(tilePrefabs[i].name))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called periodically to trim excess pooled tiles
|
||||
/// </summary>
|
||||
private void TrimExcessPooledTiles()
|
||||
{
|
||||
if (_tilePool != null)
|
||||
{
|
||||
_tilePool.TrimExcess();
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
void OnDrawGizmosSelected()
|
||||
@@ -151,8 +297,13 @@ namespace Minigames.DivingForPictures
|
||||
Gizmos.color = Color.cyan;
|
||||
for (int i = 0; i < initialTileCount; i++)
|
||||
{
|
||||
Vector3 center = new Vector3(0f, _screenBottom + i * TileHeight, 0f);
|
||||
Gizmos.DrawWireCube(center, new Vector3(10f, TileHeight, 1f));
|
||||
float height = 5f;
|
||||
if (tilePrefabs.Count > 0 && _tileHeights.TryGetValue(tilePrefabs[0], out float h))
|
||||
{
|
||||
height = h;
|
||||
}
|
||||
Vector3 center = new Vector3(0f, _screenBottom + i * height, 0f);
|
||||
Gizmos.DrawWireCube(center, new Vector3(10f, height, 1f));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user