PolygonSoundSpawn.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace PolygonArsenal
  5. {
  6. public class PolygonSoundSpawn : MonoBehaviour
  7. {
  8. public GameObject prefabSound;
  9. public bool destroyWhenDone = true;
  10. public bool soundPrefabIsChild = false;
  11. [Range(0.01f, 10f)]
  12. public float pitchRandomMultiplier = 1f;
  13. // Use this for initialization
  14. void Start()
  15. {
  16. //Spawn the sound object
  17. GameObject m_Sound = Instantiate(prefabSound, transform.position, Quaternion.identity);
  18. AudioSource m_Source = m_Sound.GetComponent<AudioSource>();
  19. //Attach object to parent if true
  20. if (soundPrefabIsChild)
  21. m_Sound.transform.SetParent(transform);
  22. //Multiply pitch
  23. if (pitchRandomMultiplier != 1)
  24. {
  25. if (Random.value < .5)
  26. m_Source.pitch *= Random.Range(1 / pitchRandomMultiplier, 1);
  27. else
  28. m_Source.pitch *= Random.Range(1, pitchRandomMultiplier);
  29. }
  30. //Set lifespan if true
  31. if (destroyWhenDone)
  32. {
  33. float life = m_Source.clip.length / m_Source.pitch;
  34. Destroy(m_Sound, life);
  35. }
  36. }
  37. }
  38. }