- Home /
Is there any way to create a dynamic material when no materials have been compiled?
In the process of creating a dynamic scene I discovered that it would not render the materials when built.
From what I can gather unless you actually compile the script with an object that has a material the resources required to build a material will not be included.
Is there any way (that I haven't been able to discover after quite a bit of searching) to dynamically create a material that will render in a build?
I seek to build everything from scripts and an empty game object. No other assets, resources, etc.
Answer by unit_nick · Sep 22, 2017 at 05:04 AM
I have found the solution.
Create a scripted shader. This can be done automatically by selecting Create > Shader in your Project folder in the editor.
You then need to create a new material with this shader. I do it by creating an object field in the inspector.
public Shader shader;
which you can drop your shader script into. Then create your materialMaterial material = new Material(shader);
And finally you attach this material to your objects
gameObject.GetComponent<Renderer>().material = material;
You might say this breaks my requirements for no other assets but because you can write the shader it meets my requirements.
I seek to build everything from scripts and an empty game object. No other assets, resources, etc.
Because I fail to see how you have addressed the above
just make sure you have all the needed assets first.
Answer by fafase · Sep 19, 2017 at 07:34 AM
You need a reference to the shader. Unity only compiles assets that are used or in the Resources/StreamingAssets folders.
If you need to create a material at runtime, just make sure you have all the needed assets first.
public class MaterialFactory:MonoBehaviour
{
[SerializeField] private Shader shader;
public Material CreateMaterial()
{
return new Material(shader);
}
}
Click the circle icon on the shader slot, it will open up the inspector, you can now assign a shader and it will be shipped with the build if you place the script on a GameObject in a scene.
Including assets means it is no longer dynamic. I want everything to be driven from a script on an empty game object. I have updated my OP to reflect this. Thanks for your response.