BlasterWeapon.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Assets.Scripts.Utils;
  2. using UnityEngine;
  3. namespace Assets.Scripts.BlasterWeapon
  4. {
  5. internal sealed class BlasterWeapon : MonoBehaviour
  6. {
  7. public GameObject Bullet;
  8. public ParticleSystem MuzzleFlashPs;
  9. public ManualLightBehavior ManualLightBehavior;
  10. public float BulletSpeed = 1;
  11. public float LifeTime = 2f;
  12. public float LifeTimeAfterCollision = 1f;
  13. public float Duration;
  14. public bool DestroyOnCollision = true;
  15. private bool _isEnabled;
  16. private ParticleSystem[] _muzzleFlashParticleSystems;
  17. private void Awake()
  18. {
  19. MuzzleFlashPs.Stop(withChildren: true);
  20. _muzzleFlashParticleSystems = MuzzleFlashPs.GetComponentsInChildren<ParticleSystem>();
  21. }
  22. private void Start()
  23. {
  24. InvokeRepeating("Fire", 1f, Duration);
  25. }
  26. private void OnEnable()
  27. {
  28. _isEnabled = true;
  29. EnableParticleSystems(_isEnabled);
  30. }
  31. private void OnDisable()
  32. {
  33. _isEnabled = false;
  34. EnableParticleSystems(_isEnabled);
  35. }
  36. private void Fire()
  37. {
  38. if (!_isEnabled)
  39. return;
  40. ManualLightBehavior.Play();
  41. MuzzleFlashPs.Play(withChildren: true);
  42. InstantiateBullet(Bullet);
  43. }
  44. private void InstantiateBullet(GameObject bullet)
  45. {
  46. var bulletGo = Instantiate(bullet, transform.position, transform.rotation);
  47. var blasterBullet = bulletGo.GetComponent<BlasterBullet>();
  48. blasterBullet.Speed = BulletSpeed;
  49. blasterBullet.LifeTime = LifeTime;
  50. blasterBullet.LifeTimeAfterCollision = LifeTimeAfterCollision;
  51. blasterBullet.DestroyOnCollision = DestroyOnCollision;
  52. Destroy(bulletGo, LifeTime);
  53. }
  54. private void EnableParticleSystems(bool isEnabled)
  55. {
  56. foreach (var particleSystems in _muzzleFlashParticleSystems)
  57. {
  58. var particleSystemsEmission = particleSystems.emission;
  59. particleSystemsEmission.enabled = isEnabled;
  60. }
  61. }
  62. }
  63. }