C# 使用纹理2D制作材质
我正试图在unity中编写一个程序。我是unity的新手,所以我知道的不多。我希望能够在代码中制作一种新的材质,只需要传入一个纹理2D。到目前为止,我正在尝试:C# 使用纹理2D制作材质,c#,unity3d,C#,Unity3d,我正试图在unity中编写一个程序。我是unity的新手,所以我知道的不多。我希望能够在代码中制作一种新的材质,只需要传入一个纹理2D。到目前为止,我正在尝试: using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.UI; public class Search : MonoBehaviour { public v
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;
}
}
使用系统集合;
使用System.Collections.Generic;
使用System.IO;
使用UnityEngine;
使用UnityEngine.UI;
公共类搜索:单一行为
{
公共void SearchEnter()
{
MyObject.GetComponent().material=LoadImage(name.ToLower());
}
Texture2D LoadImage(字符串ImageName)
{
字符串url=”file:///C:/MyFilePath“+ImageName+”.jpg”;
纹理2d-tex;
tex=新纹理2d(4,4,TextureFormat.DXT1,false);
使用(WWW=newwww(url))
{
www.LoadImageIntoTexture(tex);
GetComponent().material.mainTexture=tex;
}
返回tex;
}
}
我不能这样做,因为它不能从纹理2D转换为材质。
有人能帮我吗?首先,在
WWW
请求完成之前,您不会等待,因此您正在尝试提前访问结果
您应该在like中使用a,而不是WWW
第二个问题:不能简单地将纹理2d
转换为材质
。您必须从给定的着色器或给定的材质创建新的材质,例如使用like
首先,在WWW
请求完成之前,您不会等待,因此您尝试提前访问结果
您应该在like中使用a,而不是WWW
第二个问题:不能简单地将纹理2d
转换为材质
。您必须从给定的着色器或给定的材质创建新的材质,例如使用like
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
...
}
}
}
}
//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;
MyObject.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);