/* Returns an unused existing instance, or creates a new one if necessary */ public GameObject GetUnusedInstance() { GameObject instance; int count = _unusedInstances.Count; if (count > 0) { instance = _unusedInstances[count - 1]; instance.SetActive(true); _usedInstances.Add(instance); _unusedInstances.RemoveAt(count - 1); //Debug.Log("reusing resource: " + instance.name + "; instances left: " + (count - 1)); } else { if (ResourcesManager.Instance.logInstantiatesAndDestroys) { Debug.Log("Instantiate: " + _resourcePath); } instance = Instantiate(_resourceObject == null ? (_resourceObject = Resources.Load(_resourcePath) as GameObject) : _resourceObject) as GameObject; _usedInstances.Add(instance); // Add a PoolableResource component and set a reference to this ResourcePool PoolableResource poolableResource = instance.AddComponent <PoolableResource>(); poolableResource.resourcePool = this; //Debug.Log("new resource: " + instance.name + "; instances left: " + _unusedInstances.Count); } return(instance); }
/* Destroys the specified GameObject, or disables it and adds it to the available instances of the corresponding ResourcePool */ public void RemoveResourceInstance(GameObject instance, bool deactivateIfNotExists = false) { PoolableResource poolableResource = instance.GetComponent <PoolableResource>(); if (poolableResource != null) { poolableResource.resourcePool.FreeInstance(instance); } else { if (deactivateIfNotExists) { instance.SetActive(false); } else { if (logInstantiatesAndDestroys) { Debug.Log("Destroy: " + instance.name); } Destroy(instance); } } }