I’m making a script to play a sound when I turn on and off my flashlight, and I get these errors. How do I fix this?
IndexOutOfRangeException: Index was outside the bounds of the array.
Flashlight.Update () (at Assets/Scripts/Flashlight.cs:32)
IndexOutOfRangeException: Index was outside the bounds of the array.
Flashlight.Update () (at Assets/Scripts/Flashlight.cs:39)
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Flashlight : MonoBehaviour
{
[SerializeField] GameObject FlashlightLight;
[SerializeField] private bool useFlashlight = false;
[SerializeField] private bool FlashlightActive = false;
[SerializeField] private AudioSource flashlightAudioSource = default;
[SerializeField] private AudioClip[] flashlightOn = default;
[SerializeField] private AudioClip[] flashlightOff = default;
// Start is called before the first frame update
void Start()
{
FlashlightLight.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (useFlashlight == true)
{
if (Input.GetKeyDown(KeyCode.F))
{
if (FlashlightActive == false)
{
FlashlightLight.gameObject.SetActive(true);
FlashlightActive = true;
flashlightAudioSource.PlayOneShot(flashlightOn[UnityEngine.Random.Range(0, flashlightOn.Length - 1)]);
}
else
{
FlashlightLight.gameObject.SetActive(false);
FlashlightActive = false;
flashlightAudioSource.PlayOneShot(flashlightOff[UnityEngine.Random.Range(0, flashlightOff.Length - 1)]);
}
}
}
}
}