Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Question Create a material from shader graph asset in editor script

Discussion in 'Universal Render Pipeline' started by sstrong, Mar 2, 2022.

  1. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,195
    How can I create a material in an editor script in much the same way as I would from a shader asset?
    Code (CSharp):
    1. Shader myShader = (Shader)AssetDatabase.LoadAssetAtPath(shaderPath, typeof(Shader));
    2.  
    3. Material mat = new Material(myshader);
    4.  
    5. Material mat2 = new Material( ?? myshader.shadergraph)
     
  2. DaCookie

    DaCookie

    Joined:
    Nov 4, 2014
    Posts:
    44
    You can do that exactly like if it's a shader asset, just as you said :)

    Code (CSharp):
    1. Material material = null;
    2. Shader shader = Resources.Load<Shader>("MyShaderGraphAsset");
    3. if (shader != null)
    4. {
    5.     material = new Material(shader);
    6. }
     
  3. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,195
    This will fail unless the shader graph is in a resources folder. From the manual:

    "Loads the asset of the requested type stored at path in a Resources folder using a generic parameter type filter of type T."

    I need to load it from a specific path that is not in a Resources folder and I don't want it to be included in builds.
     
  4. ROBYER1

    ROBYER1

    Joined:
    Oct 9, 2015
    Posts:
    1,444
    Try something like this, works for me!


    Code (CSharp):
    1.                     // Create a new material with the same properties as the imported material
    2.                     Material newMaterial = null;
    3.  
    4.                     defaultShader = Shader.Find("Shader Graphs/SphereMask");
    5.  
    6.                     if (defaultShader != null)
    7.                     {
    8.                         newMaterial = new Material(defaultShader);
    9.                     }
    10.                     else
    11.                     {
    12.                         Debug.LogError("Couldn't load shader");
    13.                     }