- Home /
Question by
Kalicronic · Sep 10, 2019 at 02:25 PM ·
editor-scriptingprefabsmaterialschange material
Change prefab Material
Hey,
I have some Blender models with the same materials. The models stored as prefab in Resources.
In Unity I have a custom editor script to call this method that works.
I can load all Prefabs and their materials, but the Prefabs do not apply the new materials.
Here is my Code:
public class AutoMaterialSetter : MonoBehaviour { public string prefabsPath; public string directoryResourcesPath;
public void setMaterialToPrefabList()
{
GameObject[] prefabs = Resources.LoadAll<GameObject>(prefabsPath);
for (int prefIndex = 0; prefIndex < prefabs.Length; prefIndex++)
{
//the new materials
Material[] resourcesMaterials = Resources.LoadAll<Material>(directoryResourcesPath);
//the old materials
Material[] materials = prefabs[prefIndex].transform.GetChild(0).GetComponent<MeshRenderer>().sharedMaterials;
//swap materials
for (int materialIndex = 0; materialIndex < materials.Length; materialIndex++)
{
foreach (Material resMaterial in resourcesMaterials)
{
if (materials[materialIndex].name.Equals(resMaterial.name))
{
Debug.Log("-------------------------------------------------" +
"\nPrefab name; " + prefabs[prefIndex].name +
"\nPrefab material name; " + materials[materialIndex].name +
"\nResources material name; " + resMaterial.name);
/*Material newMat = new Material(resMaterial);
newMat.name = materials[materialIndex].name;*/
materials[materialIndex] = resMaterial;
}
}
}
//apply materials to prefab
prefabs[prefIndex].transform.GetChild(0).GetComponent<MeshRenderer>().materials = materials;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Changing the Material of an instance of a prefab only! 2 Answers
Create varying numbers of gameObjects/prefabs in sceneview? 0 Answers
How can i create a pup-up menu like the one for choose the shader on materials in unity 2019? 1 Answer
How to access empty Material slots on a ModelImporter via script? 1 Answer