使用 Unity Editor,如何从我的计算机上传文件并将其显示在 3D 对象或平面上?

Using Unity Editor, how do i upload a file from my computer and have it appear on a 3D object or plane?

我在 YouTube 上找到了一个使用 Unity 2017.3.1f1 准确地将文件资源管理器和图像上传添加到 canvas 上的 'RawImage' 的教程。

我想做的是在 'button press' 之后将相同的图像添加到 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;
    }
}

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

这是因为您的 UpdateImage 函数中的代码。 WWW 应该在协程函数中使用,因为在使用 www.texture 访问纹理之前,您需要让步或等待它完成加载或下载文件。你现在不这样做。将其更改为协程函数然后 yield 它应该可以正常工作,。

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

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

如果由于某种原因你不能使用协同程序,因为它是一个编辑器插件,那么请忘记 WWW API 并使用 File.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,然后将纹理设置为渲染器正在使用的 material 的 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;
}
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;
    }

}