- Home /
Has anyone ever used code to change the materials on an instantiated game object?
Hello! So I'm trying to change the material on a quad to a random picture whenever I load up the game. I'm using a for loop to instantiate the quad's so it would be great if I could make their materials random.
Yes I read the API and it wasn't helping me with my specific circumstance which is why I was hoping someone here could point me in the right direction.
public Material[] mats;
void levelCreate()
{
Material mat = mats[Random.Range(0, mats.Length)];
if (easy == true)
{
GetComponent<Renderer>().material = mat;
for (int i = 0; i < 5; i++) //makes the columns in the 5 by 5 grid
{
for (int j = 0; j < 6; j++) //makes the rows in a 5 by 5 grid
{
Instantiate(prefab, new Vector3(j * 1.5f - 3, i * -1.5f + 3, 0), transform.rotation);
prefab.name = count.ToString();
count++;
gameStart = false;
}
}
}
}
Oh and I read the API from http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html http://docs.unity3d.com/ScriptReference/Renderer-material.html and http://docs.unity3d.com/ScriptReference/Random.Range.html
Answer by DoTA_KAMIKADzE · Jul 18, 2015 at 11:29 AM
Something like that:
public Material[] mats;
void levelCreate()
{
Material mat = mats[Random.Range(0, mats.Length)];
if (easy == true)
{
for (int i = 0; i < 5; i++) //makes the columns in the 5 by 5 grid
{
for (int j = 0; j < 5; j++) //makes the rows in a 5 by 5 grid
{
GameObject go = Instantiate(prefab, new Vector3(j * 1.5f - 3, i * -1.5f + 3, 0), transform.rotation) as GameObject;
go.name = count.ToString();
//if you have only 1 material:
go.GetComponent<Renderer>().material = mat; //if you have multiple materials then loop through materials[X]
count++;
gameStart = false;
}
}
}
}
I've removed your line#7, get it back if it was intended, also j < 6 => j < 5.
The main part of the answer is obviously Instantiation (line #11 and #14 in my example).
Your answer
Follow this Question
Related Questions
How do i get texture from GUI box? 1 Answer
Array loop first element goes last? 1 Answer
Trouble with for loop out of range. Simple? Maybe. 1 Answer
Trouble checking against array objects 0 Answers