- Home /
Loading files via WWW class and Unity hangs for a few seconds if I use coroutines. If I don't, it works perfectly. What is going on?
So, I'm reading audio files from my hard drive using WWW and I'd like the rest of the game to keep going while the files are loading. I try to use coroutines to prevent hangups, but they actually make my game hang until all the files are loaded. And if I don't use them, it seems to work without glitches.
Can anyone explain what is going on? Why is the game hanging when I'm yielding?
Here are some code snippets.
With a coroutine
void Start()
{
Debug.Log("Reading Files...");
var audioFiles = Directory.GetFiles("audio", "*.ogg");
StartCoroutine(AddAudioFiles(audioFiles));
}
IEnumerator AddAudioFiles(string[] files)
{
foreach(var file in files)
{
Debug.Log("Begin loading url file");
WWW www = new WWW("file://"+file);
yield return www;
var clip = www.audioClip;
clips.Add(www.audioClip);
}
}
Without a coroutine (just remove the yield)
void Start()
{
Debug.Log("Reading Files...");
var audioFiles = Directory.GetFiles("audio", "*.ogg");
AddAudioFiles(audioFiles);
}
void AddAudioFiles(string[] files)
{
foreach(var file in files)
{
Debug.Log("Begin loading url file");
WWW www = new WWW("file://"+file);
var clip = www.audioClip;
clips.Add(www.audioClip);
}
}
Not sure if this is of any help (perhaps you're already doing this, I'm not that good at C#), but have you looked into Threads? http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx
Well I can't use threads with WWW, since it's part of the Unity API, but that's not the problem. WWW is asynchronous, but when I yield it blocks the main thread completely, which shouldn't happen.
Answer by appearance · Aug 23, 2013 at 08:31 AM
Try this: (Im not sure but this may have different effect)
void Start()
{
Debug.Log("Reading Files...");
var audioFiles = Directory.GetFiles("audio", "*.ogg");
StartCoroutine(AddAudioFiles(audioFiles));
}
IEnumerator AddAudioFiles(string[] files)
{
Debug.Log("Begin loading url file");
foreach(var file in files)
{
yield return StartCoroutine (LoadAudioFile (file));
}
}
IEnumerator LoadAudioFile (string url) {
WWW www = new WWW ("file://" + url);
yield return www;
var clip = www.audioClip;
clips.Add (clip);
}
IEnumerator AddAudioFiles (string[] files) {
foreach (var file in files) {
StartCoroutine (LoadAudioFile (file));
}
}
It's the same. Still no improvement. I also tried setting www.threadpriority
to ThreadPriorty.Low
, but that didn't help either.
Your answer
Follow this Question
Related Questions
How to yiled a try/catch block? 2 Answers
Yield Problems 2 Answers
How to set timer for WWW helper? 1 Answer
yield return WWW stops Coroutine? 0 Answers
yield return request never returns 2 Answers