Hi everyone, I’ve encountered a problem that I can’t understand: NullReferenceException. I’m making a simple sound player, and I want to change the name on the interface according to the name of the song and synchronize the playback progress of the song to the progress bar.
My code is following the video tutorial exactly, but it still gives an error.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SoundManager : MonoBehaviour
{
public AudioClip[ ] AudioClips;
AudioSource audioSource;
public int CurrentTrack = 0;
bool isPlaying = false;
public Text SongName;
public Slider ProgressBar;
// Start is called before the first frame update
void Start()
{
audioSource = GetComponent<AudioSource>();
audioSource.clip = AudioClips[CurrentTrack];
}
// Update is called once per frame
void Update()
{
SongName.text = AudioClips[CurrentTrack].name;
ProgressBar.maxvalue = AudioClips[CurrentTrack].length;
ProgressBar.value = audioSource.time;
}
void Play()
{
audioSource.Play();
isPlaying = true;
}
void Pause()
{
audioSource.Pause();
isPlaying = false;
}
void Stop ()
{
audioSource.Stop();
}
void Mute()
{
audioSource.mute = true;
}
void UnMute()
{
audioSource.mute = false;
}
void Next()
{
Stop();
if (CurrentTrack == AudioClips.Length - 1)
CurrentTrack = 0;
else
CurrentTrack++;
audioSource.clip = AudioClips[CurrentTrack];
if(isPlaying)
Play();
}
void Previous()
{
Stop();
if (CurrentTrack == 0)
CurrentTrack = AudioClips.Length - 1;
else
CurrentTrack--;
audioSource.clip = AudioClips[CurrentTrack];
if (isPlaying)
Play();
}
}