Audio still being played after code rectification

Even after changing the code, The ‘click’ audio is still pops up whenever I hit the play button
Here is the code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour {
    //config parameters
    [SerializeField] Paddle paddle1;
    [SerializeField] float xPush = 2f;
    [SerializeField] float yPush = 15f;
    //state
    Vector2 paddleToBallVector;
    bool hasStarted = false;

	// Use this for initialization
	void Start ()
    {
        paddleToBallVector = transform.position - paddle1.transform.position;
	}
	
	// Update is called once per frame
	void Update ()
    {
        if (!hasStarted)
        {
            LockBallToPaddle();
            LaunchOnMouseClick();
        }
    }

    private void LaunchOnMouseClick()
    {
        if (Input.GetMouseButtonDown(0))
        {
            hasStarted = true;
            GetComponent<Rigidbody2D>().velocity = new Vector2(xPush,yPush);
        }
    }

    private void LockBallToPaddle()
    {
        Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
        transform.position = paddlePos + paddleToBallVector;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (hasStarted)
        {
            GetComponent<AudioSource>().Play();
        }
    }
}

Hi Mayank,

The ‘click’ audio is still pops up whenever I hit the play button

I’m not entirely sure what you mean by this. Do you mean, when you click the mouse button to launch the ball, as the ball launches you hear a sound effect play? Or something else?

We used the below code so that the click sound that was coming even before launching the ball due to collision with paddle would vanish, however it’s not working in my file, There is still that click sound before launching the ball

private void OnCollisionEnter2D(Collision2D collision)
    {
        if (hasStarted)
        {
            GetComponent<AudioSource>().Play();
        }
    }

Do you have Play on Awake enabled on the AudioSource component?

Example;
image

1 Like

Yes, that was the issue, got it. Thank you :grin:

1 Like

Great! You’re very welcome and I’m glad you can move forward again. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms