move pooled object on collision/trigger but keep pooling it
I have a number of pooled moons that cycle past the player. The player scores when he collides with one. At the moment the moon isn't affected by the collision but I want it to disappear on collision and re-join the pool. I don't want to destroy and respawn it because its bad for performance. Any ideas? It has to be triggered by ontriggerenter2d because that's how my scoring system is set up. Thanks!
Here is my pooling code (the object move code is separate):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moonPool : MonoBehaviour
{
public int moonPoolSize = 5;
public GameObject moonPrefab;
public float spawnRate = 4f;
public float moonMin = -1f;
public float moonMax = 3.5f;
private GameObject[] moons;
private Vector2 objectPoolPosition = new Vector2 (-10f, -25f);
private float timeSinceLastSpawned;
private float spawnXPosition = 14f;
private int currentMoon = 0;
// Start is called before the first frame update
void Start()
{
moons = new GameObject [moonPoolSize];
for (int i = 0; i < moonPoolSize; i++)
{
moons [i] = (GameObject)Instantiate (moonPrefab, objectPoolPosition, Quaternion.identity);
}
}
// Update is called once per frame
void Update()
{
timeSinceLastSpawned += Time.deltaTime;
if (GameControll.instance.gameOver == false && timeSinceLastSpawned >= spawnRate)
{
timeSinceLastSpawned = 0;
float spawnYPostion = Random.Range (moonMin, moonMax);
moons[currentMoon].transform.position = new Vector2 (spawnXPosition, spawnYPostion);
currentMoon++;
if (currentMoon >= moonPoolSize)
{
currentMoon = 0;
}
}
}
}
Object pools usually have a method to fake the normal destroy by setting the game object to in-active state.
It's usually good idea to make the object pool in a generic way so you can use it with any gameobjects
Check here instructions: https://learn.unity.com/tutorial/introduction-to-object-pooling#
interesting. I got my code from a different unity learn tutorial. I wonder why they didn't do it properly.
so i followed that tutorial but am now stuck at #7 of said tutorial.
How do i convert my original instantiate code to what they say? my current code is: { moons [i] = (GameObject)Instantiate (moonPrefab, objectPoolPosition, Quaternion.identity); }
Answer by samvilm · Dec 11, 2021 at 10:07 PM
The solution that works in the end is: (in the PLAYER script)
void OnTriggerEnter2D(Collider2D col)
{
if (!isdead)
{
col.gameObject.transform.position = new Vector2 (-10f, -25f);
}
}