BulletFactory.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class BulletFactory
  5. {
  6. public enum BulletType
  7. {
  8. Bullet = 1,
  9. }
  10. // public static GameObject CreateBullet(string path)
  11. // {
  12. // GameObject bulletPrefab = Resources.Load<GameObject>("Prefabs/Bullets/"+path);
  13. // if(bulletPrefab != null)
  14. // {
  15. // return GameObject.Instantiate<GameObject>(bulletPrefab);
  16. // }
  17. //
  18. // Debuger.LogWarning("Could not find bullet prefab["+path+"]");
  19. // return new GameObject("Empty Bullet");
  20. // }
  21. private static Dictionary<string, List<GameObject>> bulletCacheDict = new Dictionary<string, List<GameObject>>();
  22. public static T CreateBullet<T>(string path)
  23. {
  24. GameObject gameObj = null;
  25. if(bulletCacheDict.ContainsKey(path) && bulletCacheDict[path].Count > 0)
  26. {
  27. gameObj = bulletCacheDict[path][0];
  28. bulletCacheDict[path].RemoveAt(0);
  29. gameObj.SetActive(true);
  30. ParticleSystem ps = gameObj.GetComponent<ParticleSystem>();
  31. if(ps != null)
  32. ps.Play();
  33. Animator animator = gameObj.GetComponent<Animator>();
  34. if(animator != null)
  35. animator.Play(0, 0, 0);
  36. }
  37. else
  38. {
  39. GameObject bulletPrefab = Resources.Load<GameObject>("Prefabs/Bullets/"+path);
  40. if(bulletPrefab != null)
  41. {
  42. gameObj = GameObject.Instantiate<GameObject>(bulletPrefab);
  43. }
  44. else
  45. {
  46. Debuger.LogWarning("Could not find bullet prefab["+path+"]");
  47. gameObj = new GameObject("Empty Bullet");
  48. }
  49. gameObj.AddComponent(typeof(T));
  50. }
  51. Bullet bullet = gameObj.GetComponent<Bullet>();
  52. bullet.path = path;
  53. bullet.Reset();
  54. return gameObj.GetComponent<T>();
  55. }
  56. public static void Recycle(string path, GameObject obj)
  57. {
  58. // Debuger.Log("Recycal Bullet["+path+"] "+obj);
  59. ParticleSystem ps = obj.GetComponent<ParticleSystem>();
  60. if(ps != null)
  61. ps.Stop();
  62. obj.SetActive(false);
  63. if(bulletCacheDict.ContainsKey(path))
  64. {
  65. bulletCacheDict[path].Add(obj);
  66. }
  67. else
  68. {
  69. List<GameObject> list = new List<GameObject>();
  70. list.Add(obj);
  71. bulletCacheDict.Add(path, list);
  72. }
  73. }
  74. public static void ClearCache()
  75. {
  76. bulletCacheDict.Clear();
  77. }
  78. }