How to add sound to paddle?

I want whenever my ball hits the paddle a specific sound should come, but not when I didn’t launch the ball. How to do that ? I was trying, but I stuck in here. Help me correct please.

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

public class Paddle : MonoBehaviour
{

[SerializeField] float screenWidthInUnits = 16f;
[SerializeField] float minX = 1f;
[SerializeField] float maxX = 15f;
[SerializeField] AudioClip hitSound;
bool hasStarted = false;

// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    float mousePosInUnits = Input.mousePosition.x / Screen.width * screenWidthInUnits;
    Vector2 paddlePos = new Vector2(mousePosInUnits, transform.position.y);
    paddlePos.x = Mathf.Clamp(mousePosInUnits, minX, maxX);
    transform.position = paddlePos;

    if (!hasStarted)
    {
        PlayOnMouseClick;
    }
}

private void PlayOnMouseClick()
{

    if (Input.GetMouseButtonDown(0))
    {
        hasStarted = true;
        AudioSource.PlayClipAtPoint(hitSound, Camera.main.transform.position);

    }

    private void OnCollisionEnter2D(Collision2D collision)
{
    AudioSource.PlayClipAtPoint(hitSound, Camera.main.transform.position);
}

}

Hi Sibam,

You could check in your OnCollisionEnter2D whether the ball collided with the paddle. The paddle has got a Paddle component assigned. You could look for it with GetComponent. Something similar is covered in this section. If you cannot make your idea work right now, try it again at the end of this section. :slight_smile:

Okay

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

Privacy & Terms