Setting a objects material in C#

I am trying to set the main texture of an material to a Texture2D. I am using this line of code to do it:
renderer.material.SetTexture("_MainTex", tex);
But it doesn’t work…

For some extra info:
I am using the Universal Render Pipeline.
The object I’m trying to set the texture of is a plane i have created in the code as well. Here is the code:

GameObject display = new GameObject("Display");
MeshFilter filter = display.AddComponent(typeof(MeshFilter)) as MeshFilter;
filter.mesh = planeMesh;
MeshRenderer renderer = display.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
renderer.material = displayMat;
renderer.material.SetTexture("_MainTex", tex);

(The “planeMesh” and “displayMat” and “tex” are defined earlier in the script)

Can someone help me?

So, what “doesn’t work”?

First suggestion is to run the code in the Editor. Check for errors, and examine the GameObject display to find out exactly how much of what you intend the code to do, actually has been done. Perhaps add some Debug Logs to see if the code actually is running.

Second line above gets a fresh copy of the material, calls SetTexture() on it and discards the result.

Instead, set the displayMat’s texture, then assign it to renderer.material

This instancing behavior is covered in the docs for the .material property:

https://docs.unity3d.com/ScriptReference/Renderer-material.html

Also, this can get more concise:

MeshRenderer renderer = display.AddComponent<MeshRenderer>();

Thank you now it works

1 Like