Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved How do I make sound play consistently on collision?

Discussion in 'Audio & Video' started by TRI99ER_, Sep 17, 2023.

  1. TRI99ER_

    TRI99ER_

    Joined:
    Aug 2, 2023
    Posts:
    11
    I have a ball object, that, when hit something, should play a sound. And it does, but not consistently (one time it can play it every time it hits anything like intended, but the other times sound only plays on some hits). In attempts to solve this, I tried lowering fixed timestep, but it doesn't seem to work.

    Here are relevant parts of the code.

    Ball.OnCollisionEnter2D:
    Code (CSharp):
    1. private void OnCollisionEnter2D(Collision2D collision) {
    2.     Debug.Log("Hit anything");
    3.     OnBounced?.Invoke(this, EventArgs.Empty);
    4. }
    SFXManager:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SFXManager : MonoBehaviour {
    4.  
    5.     [SerializeField] AudioClipsData audioClipsData;
    6.  
    7.     private void Start() {
    8.         Ball ball = Ball.Instance;
    9.  
    10.         ball.OnBounced += Ball_OnBounced;
    11.     }
    12.  
    13.     private void Ball_OnBounced(object sender, System.EventArgs e) {
    14.         PlaySound(audioClipsData.bounce, Camera.main.transform.position);
    15.     }
    16.  
    17.     private void PlaySound(AudioClip audioClip, Vector3 position, float volume = 1f) {
    18.         AudioSource.PlayClipAtPoint(audioClip, position, volume);
    19.     }
    20.  
    21. }
    22.  
    To answer some probable questions: Yes, OnCollisionEnter2D logs "Hit anything" consistently, even when no sound plays. But sound isn't playing for some reason.
    I also apologize, if it's a wrong part of forum to post this.
     
  2. TRI99ER_

    TRI99ER_

    Joined:
    Aug 2, 2023
    Posts:
    11
    Turns out it has nothing to do with Physics. The issue is with AudioSource.PlayClipAtPoint consistency. So I will close this topic and open a new one in Audio section.
     
  3. TRI99ER_

    TRI99ER_

    Joined:
    Aug 2, 2023
    Posts:
    11
    Here's a little Update.
    The issue was with audio clip. Sound has a very fast attack and no sustain, which means that it's very punchy. I guess, sometimes it was trimming the actual sound part, so nothing was heard. I solved it by adding some milliseconds of silence at the start.