- Home /
C# Music Randomizer Causing Lag
I created a music Randomizer script and for some reason it's causing a noticeable amount of lag. It's pretty small so I'm not sure why it's causing lag. Though I'm pretty sure the script is causing the lag. The lag occurs immediately after I attach the script to a gameobject and when I remove it from the gameobject the lag is gone. Any ideas as to why this is occurring?
using UnityEngine;
public class Music : MonoBehaviour {
public AudioSource audioSource;
public AudioClip[] sounds;
public AudioClip sound;
public float wait;
void Start(){
audioSource = GetComponent<AudioSource>();
sounds = Resources.LoadAll<AudioClip>("Music");
}
void Update(){
if(wait <= 0f){
sound = sounds[Random.Range(0, 10)];
audioSource.clip = sound;
audioSource.Play();
wait=sound.length;
}
else if(wait > 0f){
wait -= Time.deltaTime;
}
}
}
Are my audioClips large enough to cause this? I have 10 of them and they are around 2-5 mbs.
Answer by jmgek · Dec 04, 2015 at 02:49 AM
First I would change the way you load in the sounds at update, as it is loading a new sound every frame
private bool checkLoad = true;
void Start(){
audioSource = GetComponent<AudioSource>();
sounds = Resources.LoadAll<AudioClip>("Music");
LoadSong();
}
void Update(){
if(wait <= 0f){
audioSource.Play();
if(checkLoad == true)
LoadSong();
}
else if(wait > 0f){
wait -= Time.deltaTime;
checkLoad = true;
}
}
void LoadSong()
{
sound = sounds[Random.Range(0, 10)];
audioSource.clip = sound;
wait=sound.length;
checkLoad = false;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Pick between two floats 2 Answers
Random element from the list 1 Answer
How can I do random choices 1 Answer