- Home /
Generating new materials problem when making a prefab.
This is going to be hard to explain since I don't know the exact terminology.
I am making materials in the editor (dynamically) and applying them to generated mesh, but my problem comes when I want to turn my mesh into a prefab (with drag and drop into projects and with prefab utility), I get the "No pixel shader pink" when I try and see the prefab.
This was my code:
obj.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("SomeShaderIMade"));
I would like to keep that kind of format but I know you have to have some sort of material instanced, I have gotten it to work with using resources but it shares the material along all the objects and I need separate colors on them.
obj.GetComponent<Renderer>().sharedMaterial = Resources.Load("test") as Material;
Is there a way I can do this where I can bring in new materials and have my generated mesh produce correct prefabs?
Answer by jmgek · Dec 06, 2015 at 07:26 PM
I figured it out:
int matcount = 0;
private void ColorObject(GameObject obj)
{
matcount++;
Material mat = obj.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("MyShader"));
AssetDatabase.CreateAsset(mat, string.Format("Assets/MyMaterial{0}.mat", matcount));
obj.GetComponent<Renderer>().sharedMaterial.color = color;
}
You need to create the material into the project so it has a dynamic link to a material with AssetDatabase. also if you go this way don't create a new material every time if it's the same color just share the material across all objects that share color.
Answer by kidmosey · Dec 06, 2015 at 08:32 AM
Resources.Load() will essentially generate a pointer to the prefab.
If you want to copy it, you can use Instantiate<Material>(loadedMaterial)
Also, using sharedMaterial could be an issue. You might need to use material instead.
I understand what Resourse.load does but this is not what I am asking, shared material is because I am inheriting from the editor. and instancing still shares a material.
I appreciate the answer but in the future could you think about posting as a comment if you don't directly answer the question, others will see this as answered when it's not.
I guess I have to assign materials in groups. Thanks for your help,
Your answer
Follow this Question
Related Questions
Pressing play Causes Re-instancing of material (Editor) 1 Answer
Enable Emission to update at run time in editor 5.6.1? 2 Answers
Assign gameobject icon dynamically 0 Answers
how to link variable as inspector field 1 Answer
Changing the materials in Editor Mode Without Getting the leak Error 3 Answers