- Home /
Randomize Array, pick object and change material?
Hi everyone, today I am working with "Random", I looked up for tutorials on the subject and I found some on how to randomize through an Array, they were pretty basic and they didn't helped me with my problem. This is what I want to do:
I have 10 spheres in my scene, all of them have a simple black diffuse material, i need to store them in a GameObject Array, then Randomly pick one and change its material, how can i achieve this? I'm not asking for a precise answer, just point me out to a tutorial or give me a head start.
Thanks for your time.
Answer by Eric5h5 · Oct 21, 2012 at 05:00 AM
var objects : GameObject[];
var newMaterial : Material;
function Start () {
objects[Random.Range(0, objects.Length)].renderer.material = newMaterial;
}
I knew it!! I was trying something really alike but I don´t know why my code just picked every single sphere on the array!:
var randomIndex:int; var new$$anonymous$$aterial: $$anonymous$$aterial; var spheres: GameObject[];
function Update(){ // Get random index randomIndex = Random.Range(0,spheres.Length);
//Change material to random selected sphere spheres[randomIndex].renderer.shared$$anonymous$$aterial = new$$anonymous$$aterial;
}