- Home /
Creating a Material from shader string
Hi,
I am trying to create a material by using a string for the shader parameter as described here: http://unity3d.com/support/documentation/ScriptReference/Material.Material.html (the first constructor).
This works for shaders that are very simple and have no lighting, but slightly more complex shader can not be loaded this way. I have looked through all the documentation and have not been able to find a description of what is and what isn't allowed in materials created from string.
This is the shader I am trying to load (taken from the shader lab documentation):
Shader "Testshader" { SubShader { Pass {
CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma fragmentoption ARB_fog_exp2 #include "UnityCG.cginc"
struct v2f { V2F_POS_FOG; float3 color : COLOR0; };
v2f vert (appdata_base v) { v2f o; PositionFog( v.vertex, o.pos, o.fog ); o.color = v.normal * 0.5 + 0.5; return o; }
half4 frag (v2f i) : COLOR { return half4( i.color, 1 ); } ENDCG
}
} Fallback "VertexLit" }
And I am loading it this way:
renderMat = new Material( File.ReadAllText( Application.dataPath + "/Data/Temp/Resources/testshader.shader" ) );
It is very important that I be able to load a shader from a string for the work I am currently doing.
You're probably not doing the right thing somewhere if you say you $$anonymous$$UST have your shader CG code directly into your script code. As $$anonymous$$said, you can't have CG in strings, so think about what you're doing and you'll probably find that you can do it another way.
I'm doing something very tricky...This isn't standard content creation.
Answer by Tim Cooper · Jul 07, 2010 at 03:24 PM
Due to this being 'not supported' I worked around the issue by saving my shader to a file in the project directory then force reloading it like so:
Directory.CreateDirectory( Application.dataPath + _EditorResourcePath );
File.WriteAllText( Application.dataPath + _EditorResourcePath + "/workingshader.shader", shaderString );
Shader currentShader = Resources.Load( "workingshader" ) as Shader;
var path = AssetDatabase.GetAssetPath(currentShader);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
Material m = new Material( currentShader );
Answer by jonas-echterhoff · Jul 06, 2010 at 08:58 AM
You can not load shaders which contain Cg programs from a string at runtime, as the Cg compiler is only part of the Unity editor, not of the player. Possibly, you may be able to compile the shader in the editor, and then load the compiled shader from a string (in the inspector for the shader, click "Open compiled shader").
I am trying this from an editor script. But I do understand when you say it may not be supported. I worked around this issue as described in the answer below.
Your answer
Follow this Question
Related Questions
Imported Materials Are Null 0 Answers
Importing Maya assets with applied textures shown 0 Answers
Mesh Obj export/import WITH SHADER REFERENCE 3 Answers