Hello there!
I’ve created an AudioClip array, then the script randomly selects one clip from the array and plays it , how can I check which clip from the array is playing ?
Hello there!
I’ve created an AudioClip array, then the script randomly selects one clip from the array and plays it , how can I check which clip from the array is playing ?
/**
* None of this is tested, if you have
* issues, please work them out yourself.
* Learn from experience!
**/
// Written in C#
using System;
using UnityEngine;
using System.Collections;
public class RandomAudio : MonoBehavior
{
// Store a local copy of an empty AudioClip array
// Define your clips in your editor
// If no items display in your editor, remove the 0
public AudioClip[] audioFiles = new AudioClip[0];
// Store a local int of your audio clip ID
private int audioID = 0;
// Store a local int of your audio clip array length
private int audioLength = 0;
// When the application starts...
public void Start()
{
// Get array length, and store it
this.audioLength = this.audioFiles.Length - 1;
// If no audio,
if(this.audioLength < 1) {
// Failed, exit
Application.Quit();
}
}
public void Update()
{
// If the audio is not playing,
// Side Note: this might not be perfect syntax
if(!gameObject.audio.isPlaying) {
// Change your audioID
this.changeAudio();
}
}
private void changeAudio()
{
// Create a random instance, may need to be = new System.Random();
Random randomNumberGenerator = new Random();
// Set the audioID
this.audioID = randomNumberGenerator(0, this.audioLength);
// Set the gameObject to use the new audio clip
gameObject.audio.audioClip = audioFiles[this.audioID];
// Play the audio clip
gameObject.audio.play();
}
}