Search Unity

Script to change shader but not texture

Discussion in 'General Graphics' started by NvdL, May 28, 2017.

  1. NvdL

    NvdL

    Joined:
    Feb 22, 2017
    Posts:
    14
    Hello all,

    I am trying to change the shader of a particular game object with texture through a script in the editor (ie not during gameplay). I am using the following lines of code. However, not only the shader it changed, also the texture is changed (to the default white). What I would like to accomplish is to change the shader from default to unlit/texture but to keep the existing texture.
    Shader unlitShader = new Shader(Shader.Find("Unlit/Texture"));
    gameObj.GetComponent<Renderer>().material.shader = unlitShader;

    I also tried to do it without making a new shader with the line below. However, in that case I get the message that "Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMaterial instead."
    gameObj.GetComponent<Renderer>().material.shader = Shader.Find("Unlit/Texture");

    I hope you can give me any clues on how to proceed. Many thanks in advance!

    Best,
    Nynke
     
  2. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,493
    Store references to texture in teh script, when initializing the material, pass those texture references.
     
  3. NvdL

    NvdL

    Joined:
    Feb 22, 2017
    Posts:
    14
    Thanks for the suggestion. I found a different workaround by first creating a temporary material based on the material on the object, shanging the shader in the temporary material and putting that back on the object.
    var tempMaterial = new Material(gameObj.GetComponent<Renderer>().sharedMaterial);
    tempMaterial.shader = Shader.Find("Unlit/Texture");
    gameObj.GetComponent<Renderer>().sharedMaterial = tempMaterial;