Changing to a new shader and setting the same main texture at runtime

I’m trying to change the shader of a material at runtime. The shader (outlineShader) is set in the inspector as a public variable. That part works, but I want to keep the original main texture but that part doesn’t work. The texture is blank on the object.

//get the current main texture
Texture  tex = t.gameObject.renderer.material.mainTexture;
//change to the new shader and set the texture
Material myNewMaterial = new Material( outlineShader );

myNewMaterial.mainTexture = tex;
t.gameObject.renderer.material = myNewMaterial;

I’ve also tried this with the same result

Texture tex = t.gameObject.renderer.material.mainTexture;
t.gameObject.renderer.material.mainTexture = tex;
t.gameObject.renderer.material.shader = outlineShader;

I’ve also tried setting the shader 1st and the texture second

Texture tex = t.gameObject.renderer.material.mainTexture;
t.gameObject.renderer.material.shader = outlineShader;
t.gameObject.renderer.material.mainTexture = tex;

First example, line 7 try this instead:

myNewMaterial.SetTexture("_MainTex", tex);

“_MainTex” should match the name of the texture parameter in the shader you are going to use.

Here’s what’s working for me:

Material material = new Material(Shader.Find("Diffuse"));
material.SetTexture("_MainTex", TerrainDefinition.LoadTexture(this.Selected.Terrain.diffusePath));
material.SetTextureScale("_MainTex", new Vector2(2f, 2f));
MeshRenderer mr = change.Marker.GetComponent<MeshRenderer>();
mr.sharedMaterial = material;

Thanks tango I finally figured it out. It was called _Diffuse in my shader… So this worked for me

Texture tex = t.gameObject.renderer.material.GetTexture("_MainTex");
                        t.gameObject.renderer.material.shader = outlineShader;
                        t.gameObject.renderer.material.SetTexture("_Diffuse",  tex);