So i’ve done this before, and made code from what i remember : to change the main texture when creating materials programatically, it’s either mat.mainTexture or mat.SetTextue(“_MainTex”, tex);
When it didn’t work, i checked in the Unity docs to be sure (Unity - Scripting API: Material.mainTexture) and it seems to confirm what i remember is correct.
However, after i try to set the main texture, the main texture stays at null. Am i missing something? The texture resouce is loaded, as is the shader.
Edit : not sure if it’s important, but the shader is a custom shader i made using ShaderGraph. It’s relatively simple shader with a MainTex property. I tried “MainTex” as the name, as well as “_MainTex” but so far nothing works. I also tried mat.SetTexture(“MainTex”, tex) as well as mat.SetTexture(“_MainTex”, tex) for both names. Still no results.
Here’s the code. The goal is to load texture from resource name and create a material for it.
[Serializable]
public struct MaterialInfo
{
public string Name;
public string File;
public string Shader;
}
private void GenerateMaterial(MaterialInfo info)
{
Shader shad = Shader.Find(info.Shader);
if (shad == null)
{
return;
}
Material mat = new Material(shad);
mat.name = info.Name + "_mat";
Texture2D tex = Resources.Load<Texture2D>(info.File);
if (tex == null)
{
Debug.LogError("No texture \"" + info.File + "\" found.");
return;
}
else
{
mat.mainTexture = tex;
}
GeneratedMaterials.Add(mat);
if (Prefab != null)
{
GameObject go = GameObject.Instantiate(Prefab);
MeshRenderer mr = go.GetComponent<MeshRenderer>();
mr.material = mat;
mr.enabled = true;
go.name = info.Name + "_prefab";
}
}

