- Home /
Unity Hangs/Crash when remove GUI Button.
Quick question here. I write a loop in my GUI script and turn out okay when I attach it to a GUI button. As I remove the button so that it would appear straight away, unity hangs. Is there an error in my script? Thank You.
The part of the code:-
if(GUILayout.Button("Add"))
{
selStrings = new Texture[StackNum];
for (i = 0 ; i < selStrings.length ; i++)
{
selStrings[i] = new Texture2D(60,80, TextureFormat.RGB24, false);
www = new WWW("file://" + Application.dataPath + "/Screenshots/ScreenShot" + i + ".png");
www.LoadImageIntoTexture(selStrings[i]);
TextureScale.Bilinear (selStrings[i],133,100);
Debug.Log(i);
}
Answer by Waz · Jul 15, 2011 at 03:09 AM
Is it hanging or just going extremely slow? If you do the above in OnGUI, it will be loading those images at least 2 times every frame.
I guess it's going extremely slow. Why would it be loading twice on every frame but reacts differently when I put a button? Would you care to explain? Sorry for the noobness.
It would load them only once since Button only return true in the repaint step and only for one frame, but i guess the problem ist that you don't wait until the WWW request is finished. The WWW class works completely asynchron.
Oh I see. I did remove the yield for the WWW. Thank you very much for the explanation.
Answer by Bunny83 · Jul 15, 2011 at 03:32 AM
From the script part you're showing i can't determine what language you're using but i guess it's UnityScript.
function LoadImages()
{
selStrings = new Texture[StackNum];
for (i = 0 ; i < selStrings.length ; i++)
{
selStrings[i] = new Texture2D(60,80, TextureFormat.RGB24, false);
www = new WWW("file://" + Application.dataPath + "/Screenshots/ScreenShot" + i + ".png");
yield www; // this is important! It will suspend this coroutine until the "download" is finished
www.LoadImageIntoTexture(selStrings[i]);
TextureScale.Bilinear (selStrings[i],133,100);
Debug.Log(i);
}
}
function OnGUI()
{
if(GUILayout.Button("Add"))
{
LoadImages();
}
}
@Bunny83, is there an answer in there? Looks like you got half way through saying something.