Random audio not playing

Hello! I’m having an issue where once I added the lines of code that are supposed to play random audio clips within an array of them, it’s returning an error in the console that says IndexOutOfRangeException: Index was outside the bounds of the array. and I’m not sure why. Here’s my code:

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

public class Ball : MonoBehaviour
{
    [SerializeField] Paddle paddle1;
    [SerializeField] float xPush = 2f;
    [SerializeField] float yPush = 15f;
    [SerializeField] AudioClip[] ballSounds;


    //config parameters

    // 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();
            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)
        {
            AudioClip clip = ballSounds[UnityEngine.Random.Range(0, ballSounds.Length)];
            myAudioSource.PlayOneShot(clip);
        }
    }
}

And here’s a screenshot of my ball prefab. It looks like my audio is plugged into the array correctly.

I rewatched the lesson 3 times and I can’t figure out what I’m doing wrong. Any help would be greatly appreciated!

Try ballSounds.Length - 1

So I decided to just soldier on in the course after making this post, then for some reason while implementing the score system, the sound effects just started working again with no change in my ball.cs code. no idea why that happened.

I did go ahead and add the ballSounds.Length - 1 to my code and it still works fine, so I guess if someone is having the same problem as me, try that or just keep going till it works?

Hi Ben,

ballSounds.Length - 1 is the solution for this IndexOutOfRangeException error because the first index of an array starts with 0, not 1, thus the last index is Length - 1. Good job! :slight_smile:


See also:

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

Privacy & Terms