- Home /
Assign 1st array of materials into multiple gameobjects.
Hello guys. I'm new to Unity. I want to assign an array of materials to multiple objects. For example I have a 3d car. I want to change the color of the car into red, blue, and green. However the 3d model have many children within a gameobject so i try to use foreach on the 3d model and materials. But when i click the button it only change to one color only. Please help. Thank you.
public GameObject[] gameobjects;
public Material[] materials;
public void AssignMaterialto()
{
foreach (var obj in gameobjects)
{
foreach (Material mat in materials)
{
obj.GetComponent<Renderer> ().sharedMaterial = mat;
}
}
}
Your question is not very clear. Can you explain it better, or what your end goal is. Do you want one car that is three different colours, or three cars that each have a different colour?
I'm sorry. Actually I want one car to change into multiple color. However inside the 3d model there are multiple gameobject such as bumper, door, body, tyre. I just want to access certain part of the car to change the color. $$anonymous$$y script will look like the picture and each time I click button both or more gameobject change change into one color. Click another they will change to another color.
Like this? Note: $$anonymous$$ake sure materials and gameobjects array are the same length.
public GameObject[] gameobjects;
public $$anonymous$$aterial[] materials;
public void Assign$$anonymous$$aterialto()
{
for (int i = 0; i < gameobjects.length, i++)
{
gameobjects[i].GetComponent<Renderer> ().shared$$anonymous$$aterial = materials[i];
}
}
I tested it but it assign my 2 gameobject into 2 different color. That's okay I try change the code. Thank you.