Search Unity

Question Create shader variant from material

Discussion in 'General Graphics' started by Vifi, Feb 28, 2022.

  1. Vifi

    Vifi

    Joined:
    Aug 5, 2013
    Posts:
    28
    Hi,
    i am writting some tool to find out, which material is qualified into which shader variant in shader variants collection.
    My plan was to generate shader variant and use contains and at least to check if it is in shader variants collection. Then i could just sum the same shader variants to check how many materials is in every variant.
    Sadly i don't understand it enough to do so.
    I stopped on generating new shader variant because it needs to get PassType, which i cannot aquire.

    Code (CSharp):
    1. var item = materials[0];
    2. ShaderVariantCollection.ShaderVariant shader = new ShaderVariantCollection.ShaderVariant(item.shader,/*don't know how to get it*/, item.shaderKeywords);
    I did some research and found out (not sure if correctly) that PassType is just value of "LightMode" tag inside shader pass?
    But there might be multiple passes in shader, does it mean one shader variant is in fact one pass from shader?
    Same as there might be multiple subshaders per shader, isn't it? So every variant is one of passes inside one of subshaders from one of shaders?
    I don't think i understand it right :(
    Do you guys know how to bite it?
    Thanks in advance
    Cheers
     
  2. robin_unity63

    robin_unity63

    Joined:
    Feb 1, 2023
    Posts:
    1
    Did you ever find a solution how to find the correct PassType?
     
  3. esin03925

    esin03925

    Joined:
    Sep 16, 2022
    Posts:
    1
    I don't know is it right or not, but I made some tricky move with PassType enum to find which one pass type used in the shader variant. Hope it helps
    Code (CSharp):
    1.          
    2. // Get the materials used by the renderer
    3. Material[] materials = someRenderer.sharedMaterials;
    4.  
    5.  // Iterate through each material
    6.  foreach (Material material in materials)
    7. {
    8.        // Get the shader used by the material
    9.        foreach (PassType passType in System.Enum.GetValues(typeof(PassType)))
    10.         {
    11.              try
    12.               {
    13.                      ShaderVariantCollection.ShaderVariant shaderVariant = new(material.shader, passType, material.shaderKeywords);
    14.                      if (!shaderVariantCollection.Contains(shaderVariant)) shaderVariantCollection.Add(shaderVariant);
    15.               }
    16.               catch
    17.               {
    18.  
    19.               }
    20.         }
    21.  
    22. }
    23.