Last active
January 17, 2020 13:26
-
-
Save Streamweaver/1567f1c5c450d3ec2deb0efedce31ddf to your computer and use it in GitHub Desktop.
Example of a how I implemented a spawn manager for ObjectPool.cs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
// Example of implementing a Spawn Manager with ObjectPool.cs from | |
// https://gist.github.com/Streamweaver/b9164c538e277b9ecf85e71d84e59162 | |
public class SpawnManager : MonoBehaviour | |
{ | |
[System.Serializable] | |
public class Spawn | |
{ | |
public GameObject prefab; // pool prefab | |
public GameObject parent; // nest it for orgnization. | |
public int size; // size of pool | |
public float nextSpawn; | |
public float spawnRate; | |
public int maxSpawn; | |
public bool autoSpawn; | |
} | |
#region Singleton | |
private static SpawnManager _instance; | |
public static SpawnManager Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
GameObject go = new GameObject("SpawnManager"); | |
go.AddComponent<SpawnManager>(); | |
} | |
return _instance; | |
} | |
} | |
private void Awake() | |
{ | |
_instance = this; | |
} | |
#endregion | |
public List<Spawn> spawnList; | |
[SerializeField] | |
private bool _allowSpawn; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
foreach (Spawn item in spawnList) | |
{ | |
ObjectPool.Preload(item.prefab, item.maxSpawn * 2, item.parent); | |
} | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
if(IsSpawning()) | |
{ | |
for (int i = 0; i < spawnList.Count; i++) | |
{ | |
Spawn spawn = spawnList[i]; | |
if(Time.time > spawnList[i].nextSpawn && ObjectPool.NumberActive(spawn.prefab) < spawn.maxSpawn) | |
{ | |
spawn.nextSpawn = Time.time + spawn.spawnRate * Random.Range(0.5f, 1.5f); | |
GameObject go = ObjectPool.Spawn(spawn.prefab, ViewManager.Instance.NewSpawnInPosition(), Quaternion.identity, spawn.parent); | |
ISpawnable spawnedGo = go.GetComponent<ISpawnable>(); | |
if (spawnedGo != null) | |
{ | |
spawnedGo.OnSpawn(); | |
} | |
} | |
} | |
} | |
} | |
public void AllowSpawn(bool allow) | |
{ | |
_allowSpawn = allow; | |
} | |
public bool IsSpawning() | |
{ | |
return _allowSpawn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment