ImpactSoundPlayer.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using UdonSharp;
  2. using UnityEngine;
  3. [UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)]
  4. [DisallowMultipleComponent]
  5. [AddComponentMenu("Artyom Scripting System/Impact Sound Player")]
  6. public class ImpactSoundPlayer : UdonSharpBehaviour
  7. {
  8. public GameObject smallImpactSoundObject; // GameObject for small impact sound
  9. public GameObject mediumImpactSoundObject; // GameObject for medium impact sound
  10. public GameObject largeImpactSoundObject; // GameObject for large impact sound
  11. public float mediumImpactThreshold = 5.0f; // Threshold for medium impact
  12. public float largeImpactThreshold = 10.0f; // Threshold for large impact
  13. [Tooltip("Impacts slower than this play nothing. 0 plays a sound for every contact, however gentle.")]
  14. public float minimumImpact = 0f;
  15. [Tooltip("Seconds after a sound before the next can play. 0 means no limit.")]
  16. public float cooldown = 0f;
  17. private float nextSoundTime;
  18. private void OnCollisionEnter(Collision collision)
  19. {
  20. float impactForce = collision.relativeVelocity.magnitude;
  21. if (impactForce < minimumImpact || Time.time < nextSoundTime) return;
  22. nextSoundTime = Time.time + cooldown;
  23. if (impactForce >= largeImpactThreshold)
  24. {
  25. PlaySound(largeImpactSoundObject);
  26. }
  27. else if (impactForce >= mediumImpactThreshold)
  28. {
  29. PlaySound(mediumImpactSoundObject);
  30. }
  31. else
  32. {
  33. PlaySound(smallImpactSoundObject);
  34. }
  35. }
  36. private void PlaySound(GameObject soundObject)
  37. {
  38. if (soundObject != null)
  39. {
  40. soundObject.SetActive(false); // Reset the sound object
  41. soundObject.SetActive(true); // Activate the sound object to play the sound
  42. }
  43. }
  44. }