Question by
Erven · Nov 01, 2015 at 02:26 PM ·
material color
Random enemy color
I have a function randomly spawning 15 enemies, with random scale and now Im trying to assign a random color for each of them.
void Start()
{
mat = GetComponent<Material> ();
for (int i = 0; i < 15; i++)
{
float s = Random.Range (1F,15F); //size
Vector3 position = new Vector3(Random.Range(-100.0F, 100.0F),Random.Range(-100.0F, 100.0F), Random.Range(-100.0F, 100.0F));//position
Instantiate(prefab, position, Quaternion.identity);
prefab.transform.localScale = new Vector3(s,s,s);
randomNumber = Random.Range(1,3); //material
switch (randomNumber)
{
case 1:
GetComponent<Renderer>().material.color = Color.yellow;
break;
case 2:
GetComponent<Renderer>().material.color = Color.blue;
break;
case 3:
GetComponent<Renderer>().material.color = Color.green;
break;
}
}
}
This function changes the color of player. How to change it to assign randomly to enemy?
Comment
Best Answer
Answer by Statement · Nov 01, 2015 at 02:35 PM
First: Don't change the prefabs scale. Change the enemy clones scale.
Instantiate(prefab, position, Quaternion.identity);
prefab.transform.localScale = new Vector3(s,s,s); // Please don't mess with the prefab
Change it to this:
GameObject enemy = (GameObject) Instantiate(prefab, position, Quaternion.identity);
enemy.transform.localScale = new Vector3(s,s,s);
Ok, so you want to change the color of the enemy, so get the renderer of the enemy.
Renderer enemyRenderer = enemy.GetComponent<Renderer>();
Then you can just set the color to something
enemyRenderer.material.color = Color.red;
Your answer
