Default-Material (Instance)
I want to set the material of multiple objects stored in an array to mats. But the material beeing set is not mat but "Default-Material (Instance)". I checked that mat is the right Material so that is not the problem. Help plz - thx
foreach (GameObject GO in gameobjectarray) { GO.GetComponent().materials[1] = mats; }
Answer by Vicarian · Jan 24, 2017 at 06:49 PM
@maikmayo The code you've supplied isn't valid. If you want to swap a material at runtime, you have to access the GameObject's renderer, then iterate through the materials collection on the renderer. I'm unsure of how the variable mats is defined, but from usage, it's clearly a single material, so:
foreach (GameObject GO in gameobjectarray)
{
if (GO.GetComponent<Renderer>())
{
// This will swap all materials on the Renderer to mats
//foreach (Material m in GO.GetComponent<Renderer>().materials)
// m = mats;
// This will swap only the 1th material in the Renderer to mats
if (GO.GetComponent<Renderer>().materials.Count() >= 2)
GO.GetComponent<Renderer>().materials[1] = mats;
}
}
Your answer

Follow this Question
Related Questions
Accessing shader colors 1 Answer
Render Pipeline Material Issue 1 Answer
How to call all instances of a script in a list 0 Answers
Assigning a sharedMaterial to multiple renderers that change together 0 Answers
material color not changing 1 Answer