In my game the player can interact with certain objects like coins, clouds and springs. After these interactions the game objects are destroyed. All of these game objects have their own properties, but their classes inherit from a master "WorldObjects" class that contains respawn information:
protected virtual void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
if (respawnObject)
{
Respawner.respawnPositions.Add(startPosition);
Respawner.respawnTimes.Add(respawnTimer);
}
PlayerController = other.GetComponent<CharacterController2D>();
}
else return;
}
I have been able to respawn one type of object at a time by dragging a prefab to the first position in my objectsToRespawn array, but how do I send information to my Respawner class so that I can dynamically respawn the correct type of game object depending on the object I previously destroyed? Is it possible to compare my destroyed game object's name with its associated prefab, and then load the prefab into the array (or, if needed, a list)?
Here's my respawner class:
public class Respawner : MonoBehaviour
{
public GameObject[] objectsToRespawn;
public List<Vector3> respawnPositions = new List<Vector3>();
public List<float> respawnTimes = new List<float>();
private void Update ()
{
if (respawnPositions.Count != 0)
{
RespawnObjects();
}
}
private void RespawnObjects()
{
for (int i = 0; i < respawnPositions.Count; i++)
{
respawnTimes[i] -= Time.deltaTime;
if (respawnTimes[i] <= 0)
{
Instantiate(objectsToRespawn[i], respawnPositions[i], Quaternion.Euler(0, 0, 0));
respawnPositions.RemoveAt(i);
respawnTimes.RemoveAt(i);
}
}
}
Perhaps I should clarify, what I want to have happen is when I destroy a game object via OnTriggerEnter2D (like picking up a coin), that object sends its name or type or some sort of identification to the respawner class, which "queues" up the associated prefab, ultimately respawning it in its original location once the respawn timer for that object is 0.
This is my coin's OnTriggerEnter2D class (where the object is destroyed):
protected override void OnTriggerEnter2D(Collider2D other)
{
base.OnTriggerEnter2D(other);
Destroy(this.gameObject);
Destroy(Instantiate(interactionEffect.gameObject, ObjectTransform.position, ObjectTransform.rotation) as GameObject,
interactionEffect.main.duration * 2);
}