1

我在 YouTube 上找到了一个教程,该教程使用 Unity 2017.3.1f1 准确地将文件资源管理器和图像上传到画布上的“RawImage”。

在此处输入图像描述

我要做的是在“按下按钮”后将相同的图像添加到 3D 对象,如彩色立方体所示的立方体或平面。当我运行以下代码时,它注册为存在于多维数据集上但不呈现。任何帮助表示赞赏。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;

public class Explorer : MonoBehaviour
{
    string path;
    public RawImage image;

    public void OpenExplorer()
    {
        path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
        GetImage();
    }

    void GetImage()
    {
        if (path != null)
        {
            UpdateImage();
        }
    }
    void UpdateImage()
    {
        WWW www = new WWW("file:///" + path);
        image.texture = www.texture;
    }
}
4

2 回答 2

3

您的代码中有一个小错误。它有时应该工作,有时会失败。它工作与否的机会取决于图像的大小。如果图像真的很小,它会起作用,但当图像很大时会失败。

这样做的原因是因为您的UpdateImage函数中的代码。应该在WWW协程函数中使用,因为在使用www.texture. 你现在不这样做。将其更改为协程函数,然后生成它,它应该可以正常工作。

void GetImage()
{
    if (path != null)
    {
        StartCoroutine(UpdateImage());
    }
}

IEnumerator UpdateImage()
{
    WWW www = new WWW("file:///" + path);
    yield return www;
    image.texture = www.texture;
}

如果由于某种原因你不能使用协程,因为它是一个编辑器插件,那么忘记WWWAPI 并使用 useFile.ReadAllBytes来读取图像。

void GetImage()
{
    if (path != null)
    {
        UpdateImage();
    }
}

void UpdateImage()
{
    byte[] imgByte = File.ReadAllBytes(path);
    Texture2D texture = new Texture2D(2, 2);
    texture.LoadImage(imgByte);

    image.texture = texture;
}

要将图像分配给 3D 对象,请获取MeshRenderer然后将纹理设置为mainTexture渲染器正在使用的材质:

//Drag the 3D Object here
public MeshRenderer mRenderer;

void UpdateImage()
{
    byte[] imgByte = File.ReadAllBytes(path);
    Texture2D texture = new Texture2D(2, 2);
    texture.LoadImage(imgByte);

    mRenderer.material.mainTexture = texture;
}
于 2018-04-27T07:00:03.903 回答
0
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.IO;


public class Explorer : MonoBehaviour 

{
string path;
public MeshRenderer mRenderer;

public void OpenExplorer()
{
        path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
        GetImage();
}

void GetImage()
{
    if (path != null)
    {
        UpdateImage();
    }
}
    void UpdateImage()
{
    byte[] imgByte = File.ReadAllBytes(path);
    Texture2D texture = new Texture2D (2, 2);
    texture.LoadImage(imgByte);

    mRenderer.material.mainTexture = texture;

    //WWW www = new WWW("file:///" + path);
    //yield return www;
    //image.texture = texture;
    }

}
于 2018-04-28T11:33:25.487 回答