Skip to content

Instantly share code, notes, and snippets.

@Q-Bert-Reynolds
Created April 7, 2020 18:36
Show Gist options
  • Save Q-Bert-Reynolds/2c3609531aadebc2bfb229e9756bc43f to your computer and use it in GitHub Desktop.
Save Q-Bert-Reynolds/2c3609531aadebc2bfb229e9756bc43f to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public static Spawner spawner;
public GameObject[] prefabs;
List<GameObject>[] pools;
void Awake ()
{
if (spawner == null)
{
spawner = this;
DontDestroyOnLoad(gameObject);
Setup();
}
else
{
Debug.Log("Spawner already exists, destroying this one.");
Destroy(gameObject);
}
}
void Setup ()
{
pools = new List<GameObject>[prefabs.Length];
for (int i = 0; i < prefabs.Length; i++)
{
pools[i] = new List<GameObject>();
}
}
public static GameObject GetPrefab(string objName)
{
for (int i = 0; i < spawner.prefabs.Length; i++)
{
if (objName == spawner.prefabs[i].name) return spawner.prefabs[i];
}
return null;
}
public static GameObject Spawn (string objName, Vector3 pos)
{
for (int i = 0; i < spawner.prefabs.Length; i++)
{
if (objName == spawner.prefabs[i].name)
{
GameObject g = spawner.pools[i].Find(CanUse);
if (g == null)
{
g = Instantiate(spawner.prefabs[i]) as GameObject;
spawner.pools[i].Add(g);
}
g.transform.position = pos;
g.transform.SetParent(spawner.transform);
g.SetActive(true);
return g;
}
}
return null;
}
static bool CanUse (GameObject g)
{
return !g.activeSelf;
}
public static void DisableAll()
{
for (int i = 0; i < spawner.prefabs.Length; i++)
{
for (int j = 0; j < spawner.pools[i].Count; j++)
{
spawner.pools[i][j].SetActive(false);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment