我正试着统一编写一个程序。我对统一性很陌生,所以我不知道,我希望能够在我的代码中创建一个新的材料,只需要一个texture2d就可以传递给它。到目前为止,我正在尝试:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class Search : MonoBehaviour
{
public void SearchEnter()
{
MyObject.GetComponent<Image>().material = LoadImage(name.ToLower());
}
Texture2D LoadImage(string ImageName)
{
string url = "file:///C:/MyFilePath" + ImageName + ".jpg";
Texture2D tex;
tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
using (WWW www = new WWW(url))
{
www.LoadImageIntoTexture(tex);
GetComponent<Renderer>().material.mainTexture = tex;
}
return tex;
}
}我不能这样做,因为它不能从texture2d转换为材料。有谁可以帮我?
发布于 2019-07-07 16:07:38
首先,您不是在等待,直到WWW请求完成,所以您正在尝试提前访问结果。
与其使用WWW,不如在柯鲁丁中使用UnityWebRequestTexture.GetTexture,如
public class Search : MonoBehaviour
{
public void SearchEnter()
{
StartCoroutine(LoadImage(name.ToLower()))
}
IEnumerator LoadImage(string ImageName)
{
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture("file:///C:/MyFilePath" + ImageName + ".jpg"))
{
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
// Get downloaded texture
var texture = DownloadHandlerTexture.GetContent(uwr);
//TODO now use it
...
}
}
}
}第二个问题:您不能简单地将Texture2D转换为Material。您需要从给定的着色器创建一个新的Material,或者使用new Material()创建一个给定的Material,例如使用Shader.Find
//TODO now use it
// ofcourse again you can not simply create a new material from a texture
// you would rather need to pass in a shader like
var material = new Material(Shader.Find("UI/Default"));
material.mainTexture = texture;
MyObject.GetComponent<Image>().material = material;
GetComponent<Renderer>().material.mainTexture = texture;然而,对于一个Image,实际上您可能更愿意只使用默认的UI材料,而是使用一个Sprite
MyObject.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f); https://stackoverflow.com/questions/56923115
复制相似问题