纹理数组仅获取最后一个索引(C#UNITY)

时间:2018-05-07 06:27:35

标签: c# android unity3d

我正在创建一个Texture数组,所以我就是这样做的

[SerializeField] GameObject[] uitex = new GameObject[4];

void GetTextureFromServer()
{
    string dealer_image = "";
    var tex = new Texture2D(20, 20);

    for (int i = 0; i < tzPlayInfo.Instance.bc_gametablelist.Count; i++)
    {
        dealer_image += tzPlayInfo.Instance.bc_gametablelist[i].dlrimage;
        dealer_image += ",";

    }
    string[] NewLinks = dealer_image.Split(',');


    for(int j = 0; j < NewLinks.Length - 1; j++)
    {
        Debug.Log("HERE ARE THE LINKS : " + NewLinks[j]);

        new BestHTTP.HTTPRequest(new System.Uri("***********.amazonaws.com/resources" + "/dealer/pic/" + NewLinks[j]),
            (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) =>
            {
                tex.LoadImage(res.Data);
            }).Send();
    }

    for (int i = 0; i < uitex.Length; i++)
    {
        uitex[i].GetComponent<UITexture>().mainTexture = tex;
    }
}

到目前为止我尝试的是

uitex[j].GetComponent<UITexture>().mainTexture = tex;

但是它给了我一个阵列超出范围而且我不知道为什么。

这段代码的问题在于它总是得到我拥有的最后一个索引所以所有4个游戏对象都具有相同的所有纹理,这不是我想要的。有人可以帮我解决我的问题。谢谢。

2 个答案:

答案 0 :(得分:0)

在第二个for循环中,将纹理加载到tex变量中。但是你不能做任何事情,所以当for循环结束时,tex变量保存你在第三个for循环中设置的最后一个加载纹理。我不确定你的tzPlayInfo.Instance.bc_gametablelist类型是什么,但我建议重写:

for (int i = 0; i < tzPlayInfo.Instance.bc_gametablelist.Count; i++)
{
    dealer_image += tzPlayInfo.Instance.bc_gametablelist[i].dlrimage;

    Debug.Log("HERE ARE THE LINKS : " + dealer_image);

    new BestHTTP.HTTPRequest(new System.Uri("***********.amazonaws.com/resources" + "/dealer/pic/" + dealer_image),
        (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) =>
        {
            tex.LoadImage(res.Data);
            uitex[i].GetComponent<UITexture>().mainTexture = tex;
        }).Send();
}

可能存在错误,因为我无法对其进行测试,但我希望您能够理解。

答案 1 :(得分:-1)

for (int i = 0; i < tzPlayInfo.Instance.bc_gametablelist.Count; i++)
    {
        dealer_img += tzPlayInfo.Instance.bc_gametablelist[i].dlrimage;
        dealer_img += ",";
    }
    string[] newLinks = dealer_img.Split(',');

    for (int i = 0; i < newLinks.Length - 1; i++)
    {
        var index = i;  // We need to make a local copy because C# captures variables by reference to lambdas.
        new BestHTTP.HTTPRequest(new System.Uri("***************.amazonaws.com/resources/"
            + "dealer/pic/" + newLinks[index]),
            (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
            =>
            {
                var tex = new Texture2D(20, 20);
                tex.LoadImage(res.Data);
                uitex[index].GetComponent<UITexture>().mainTexture = tex;
            }).Send();
    }

想出了这个