使用新的UI Image组件在Unity 4.6中显示Web上的图像

Fel*_*lva 3 unity-game-engine unityscript

我正在尝试使用Unity 4.6中的新UI对象来创建排名屏幕,我在其中下载有关用户的信息并显示它们.在这些信息中,我有一个指向其图片的URL.

在UI工具之前,我使用GUITexture并使用www.LoadImageIntoTexture方法,但似乎没有类似的UI图像解决方案.使用带有Rect变换的GUITexture似乎不起作用.

我应该手动下载图像并将其加载到图像中,还是使用类似于使用WWW类的解决方案?

Ven*_*ios 9

新的Image组件需要一个sprite来渲染.应该做的是使用WWW类下载PNG纹理,然后创建一个精灵,最后将其分配给组件.

这是一些示例代码.

  1. 创建一个新的Monobehaviour,将下面的代码粘贴到其中(我称我的脚本为"LoadImageToButton")
  2. 创建一个新的UIButton
  3. 将步骤1中创建的Monobehaviour附加到Button
  4. 在Button的"OnClick"事件中,将在步骤2中创建的按钮(此相同按钮)拖动到GameObject字段中
  5. 选择"LoadImage"函数作为调用OnClick事件的函数.(在我的例子中是"LoadImageToButton.LoadImage")
  6. 单击"播放",单击按钮.您应该看到按钮的图像更改(它看起来很糟糕,但它有效)

有关实际结果,请参阅附带的图片.

    //This is the method you call if you use the "OnClick" event from a button click.
    //We cannot call the Coroutine function below, because it breaks the rule for
    //the event system. i.e. Must be a return type of void.

    public void LoadImage () {
        //Call the actual loading method
        StartCoroutine(RealLoadImage());
    }


    //This is where the actual code is executed
    private IEnumerator RealLoadImage () {

        //A URL where the image is stored
        string url = "http://www.axsu3d.com/DLs/AxSWP8Plugin/TileLogo.png";  

        //Call the WWW class constructor
        WWW imageURLWWW = new WWW(url);  

        //Wait for the download
        yield return imageURLWWW;        

        //Simple check to see if there's indeed a texture available
        if(imageURLWWW.texture != null) {

            //Construct a new Sprite
            Sprite sprite = new Sprite();     

            //Create a new sprite using the Texture2D from the url. 
            //Note that the 400 parameter is the width and height. 
            //Adjust accordingly
            sprite = Sprite.Create(imageURLWWW.texture, new Rect(0, 0, 400, 400), Vector2.zero);  

            //Assign the sprite to the Image Component
            GetComponent<UnityEngine.UI.Image>().sprite = sprite;  
        }

        yield return null;
    }
Run Code Online (Sandbox Code Playgroud)


在单击按钮之前. 请注意

下载并更改精灵后. 雪碧看起来很糟糕,但它确实有效