how can I get my prefab to have a different material on instantiation
Im stuck on how i can get my game object prefab to have a randomly selected material out of three different ones on each instantiation. This is the code i have:
void Start ()
{
rend = GetComponent<Renderer>();
mInital = rend.material;
myTransform = transform;
colourSelect = Random.Range(0, 3);
switch (colourSelect)
{
case 1:
mInital = mRed;
break;
case 2:
mInital = mBlue;
break;
case 3:
mInital = mYellow;
break;
}
I would appreciate it if anyone could help. Im just trying to teach myself everything about Unity :)
Answer by Statement · Nov 07, 2015 at 11:49 PM
I guess it should end with rend.material.color = mInitial;
But also, keep in mind that Random.Range(0, 3) can return values 0, 1 or 2. Not 1, 2 or 3. Your code will wither keep the original color or use red/blue but never yellow.
You could also make it a little easier to change:
public Color[] colors = { Color.red, Color.blue, Color.yellow };
void Start()
{
var renderer = GetComponent<Renderer>();
if (colors.Length > 0)
renderer.material.color = colors[Random.Range(0, colors.Length)];
}
Now you don't have to limit yourself to 3 colors.
Thank you, that code was really helpful. I am just wondering that doesn't take the materials I made, right? If I had a different Texture or material I would have to do this another way im assu$$anonymous$$g.
I don't understand what you mean. It'll change the color of the material assigned to the renderer of the game object. It doesn't "take" anything. It modifies whatever is on there.
Actually, it doesn't modify the source material, it creates a copy of the material and modifies it (otherwise it would be modifying the original asset, which would likely be annoying as it would modify every single object using that material).
But it doesn't matter which material the renderer happens to have at Start. You can change material or texture. The only thing that matters in this case is that the shader the material is using actually make use of the main color property.
If you want to replace the material of the renderer ins$$anonymous$$d of modifying the material, you can just do renderer.shared$$anonymous$$aterial = materials[Random.Range(0, materials.Length];