我有一个 CustomRenderTexture 链接到一个材质,该材质包含一个带有两个颜色参数的着色器图。我想随机设置颜色并将它们渲染到不同模型的主纹理。在下面的代码中,立方体都具有相同的颜色,可能是因为材质在整个场景中共享。
public Material mat;
void Start()
{
GameObject[] cubes = GameObject.FindGameObjectsWithTag("cube");
foreach (var cube in cubes)
{
Color randomColor1 = Random.ColorHSV();
Color randomColor2 = Random.ColorHSV();
mat.SetColor("_Color1", randomColor1);
mat.SetColor("_Color2", randomColor2);
CustomRenderTexture crt = new CustomRenderTexture(16, 16);
crt.initializationMaterial = mat;
crt.initializationSource = CustomRenderTextureInitializationSource.Material;
crt.initializationMode = CustomRenderTextureUpdateMode.OnLoad;
cube.GetComponent<Renderer>().material.SetTexture("_MainTex", crt);
}
}
我需要将它渲染到许多 MainTex Texture2D,以便 3D 中的画图可以编辑它们。
基于此: 在 Unity 2019 中将 RenderTexture 转换为 Texture2D
这给出了一个黑色的 Texture2D MainTex/反照率:
Texture2D tex = new Texture2D(16, 16, TextureFormat.ARGB32, false);
RenderTexture.active = crt;
tex.ReadPixels(new Rect(0, 0, 16, 16), 0, 0);
tex.Apply();
cube.GetComponent<Renderer>().material.SetTexture("_MainTex", tex);
这会保留默认材质,但会变暗一些
Texture2D tex = new Texture2D(16, 16, TextureFormat.ARGB32, false);
Graphics.CopyTexture(crt, tex);
tex.Apply(false);
cube.GetComponent<Renderer>().material.SetTexture("_MainTex", tex);
这也给出了一个黑色的 Texture2D MainTex/反照率:
Texture2D tex = new Texture2D(16, 16, TextureFormat.ARGB32, false);
Graphics.CopyTexture(crt, tex);
//tex.Apply(false);
cube.GetComponent<Renderer>().material.SetTexture("_MainTex", tex);
注:
Debug.Log("format: " + crt.format);
显示:ARGB32