Having problem with sound - Block Breaker

Hey everyone, I’m having a problem about getting a sound. Sound is played only when ball touches LoseCollider object. (as you can see below) When ball hits the bricks or left collider, right collider or top collider, I get no sound.

here is my Ball script.

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

public class Ball : MonoBehaviour
{
// config parameters
[SerializeField] Paddle paddle1;
[SerializeField] float shootX = 2f;
[SerializeField] float shootY = 15f;
[SerializeField] AudioClip ballSounds;

//state
Vector2 paddleToBallVector;

bool HasStarted = false;

// Cached component references
AudioSource myAudioSource;


// Start is called before the first frame update
void Start()
{
    paddleToBallVector = transform.position - paddle1.transform.position;
    myAudioSource = GetComponent<AudioSource>();
}

// Update is called once per frame
void Update()
{
    if (!HasStarted)
    {
        LockBallToPaddle();
        ShootBall();
    }
}
private void ShootBall()
{
    if (Input.GetMouseButtonDown(0))
    {
        HasStarted = true;
        GetComponent<Rigidbody2D>().velocity = new Vector2(shootX, shootY);
    }
}

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

private void OnTriggerEnter2D(Collider2D collision)
{
    if (HasStarted)
    {
        AudioClip clip = ballSounds[UnityEngine.Random.Range(0, ballSounds.Length)];
        myAudioSource.PlayOneShot(clip);
    }
}

}

also, screenshot of ball objeckt.

Okay, I fixed it.

My code was wrong.

Instead of

private void OnTriggerEnter2D(Collider2D collision)

I should use

private void OnCollisionEnter2D(Collision2D collision)

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

Privacy & Terms