简体   繁体   English

当我使用www时Unity3D冻结主线程(加载纹理)

[英]Unity3D freezing main thread when i using www (load texture)

Hello i load texture this code: settingSplit this is string array. 您好我加载纹理此代码:settingSplit这是字符串数组。

IEnumerator DownloadLogos()
{
    WWW www = new WWW(settingsSplit[0]);
    while (www.progress < 1)
    {
        slider.GetComponent<UISlider>().value = www.progress;
        if (slider.GetComponent<UISlider>().value > 0.880f)
        {
            slider.GetComponent<UISlider>().value = 1;
        }
        yield return new WaitForEndOfFrame();
    }
    yield return www;

    if (www.error == null)
    {
        fadein = true;
        model.GetComponent<Animation>().Play();
        texTmp = www.textureNonReadable;
        spr = Sprite.Create(texTmp, new Rect(0, 0, texTmp.width, texTmp.height), Vector2.zero, 50);
        spr.texture.wrapMode = TextureWrapMode.Clamp;
        mat.mainTexture = spr.texture;
        decal.sprite = spr;
        yield return new WaitForEndOfFrame();
        slider.SetActive(false);
        float multipier = 1;

        if (settingsSplit[2] != null)
        {
            multipier = float.Parse(settingsSplit[2]);
        }

        decal.transform.localScale = new Vector3(decal.transform.localScale.x * multipier,
            decal.transform.localScale.y * multipier, decal.transform.localScale.z);
        BuildDecal(decal);
    }

Work fine but When texture load MainThread stop for some time (1-2 second). 工作正常,但是当纹理加载MainThread停止了一段时间(1-2秒)。 How i can fix this ? 我该如何解决? Thanks! 谢谢!

I don't know if you have solved this, but I was facing the same problem. 我不知道您是否解决了这个问题,但是我也面临着同样的问题。 The problematic line is 有问题的线是

spr = Sprite.Create(texTmp, new Rect(0, 0, texTmp.width, texTmp.height), Vector2.zero, 50);

Because the creation of the Sprite takes a while and runs in the main thread, which causes your game to freeze. 因为Sprite的创建需要花一些时间并在主线程中运行,这会导致游戏冻结。

My solution was to use a RawImage instead of an Image to display the loaded texture, just delete the mentioned line and replace 我的解决方案是使用RawImage而不是Image来显示加载的纹理,只需删除提到的行并替换

decal.sprite = spr;

with

decal.texture = www.texture;

and set the rest of properties/values you want to use. 并设置要使用的其余属性/值。

I hope this helps someone having this problem. 我希望这可以帮助有此问题的人。

WaitForEndOfFrame resumes at the end of the frame. WaitForEndOfFrame在帧的结尾处恢复。 I'm fairly certain if you yield for the end of the frame, at the end of the frame, you still wont progress to the next frame. 我可以肯定地说,如果您在帧末尾屈服,那么在帧末尾,您仍然不会前进到下一帧。 Just yield null and you will resume the next frame. 仅产生null,您将继续下一帧。

while (www.progress < 1)
{
    slider.GetComponent<UISlider>().value = www.progress;
    if (slider.GetComponent<UISlider>().value > 0.880f)
    {
        slider.GetComponent<UISlider>().value = 1;
    }
    yield return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM