2017-04-17 65 views
0

這是Button組件的層次結構。使用腳本工作不正確的Unity材質渲染

按鈕

  • 圖片

  • 文本

用於渲染腳本如下:

for(int ii = 0; ii < idlist.Count; ii++){ 

        GameObject addTypeButton = (GameObject)Instantiate(prefabButton); 
        addTypeButton.transform.SetParent(ParentPanel, false); 
        var mybutton = addTypeButton.GetComponent<MyButton>(); 

        //set text 
        mybutton.text.text = (string)sometext[ii];  

        //get image 
        WWW www = new WWW((string)someImageUrl[ii]); 
        yield return www; 

        //set image 
        var b64_bytes = System.Convert.FromBase64String(www.text); 
        Texture2D tex = new Texture2D(1, 1, TextureFormat.RGB24, false); 
        tex.EncodeToPNG(); 
        tex.LoadImage(b64_bytes); 
        //yield return new WaitForSeconds (5) ; 

        mybutton.image.material.mainTexture = tex; 

        //testing 
        File.WriteAllBytes(Application.dataPath + "/../Saved["+ii +"].png", b64_bytes); 
} 

測試命令生成適當的IM年齡在序列中。 但是,在Unity中,圖像呈現在下一個對象上。 Here's the Screenshot

我究竟在哪裏出錯?

回答

0

請勿使用WWW.text加載圖像。這就是WWW.bytes。所以,你的System.Convert.FromBase64String(www.text);應該被刪除。您也不需要Texture2D.EncodeToPNG();功能,因爲您下載的圖像已經在pngjpeg格式。直接保存下載的圖像字節。

最後,如果你希望你的儲蓄東西在每個平臺上都能正常工作,你必須使用Application.persistentDataPath而不是Application.dataPath。您還應該使用Path.Combine來連接路徑,而不是手動進行。

for (int ii = 0; ii < idlist.Count; ii++) 
{ 

    GameObject addTypeButton = (GameObject)Instantiate(prefabButton); 
    addTypeButton.transform.SetParent(ParentPanel, false); 
    var mybutton = addTypeButton.GetComponent<MyButton>(); 

    //set text 
    mybutton.text.text = (string)sometext[ii]; 

    //get image 
    WWW www = new WWW((string)someImageUrl[ii]); 
    yield return www; 

    //set image 
    byte[] downloadedImage = www.bytes; 
    Texture2D tex = new Texture2D(1, 1, TextureFormat.RGB24, false); 
    tex.LoadImage(downloadedImage); 
    //yield return new WaitForSeconds (5) ; 

    mybutton.image.material.mainTexture = tex; 

    //testing 
    string savePath = Application.persistentDataPath; 
    savePath = Path.Combine(savePath, "images"); 
    savePath = Path.Combine(savePath, ii.ToString()); 
    savePath = Path.Combine(savePath, ".png"); 

    File.WriteAllBytes(savePath, downloadedImage); 
} 
+0

感謝您的建議。 那麼,問題依然存在。 圖像呈現在下一個對象上,而不是當前對象上。 (如問題中的截圖所示) – MAUT

+0

什麼是'idlist'? – Programmer

+0

將idlist.Count視爲元素數量。 它只是一個數據ID的數組。 – MAUT