- Home /
How to have different textures for cloned gameobject (instantiated)
I have a grass and dirt texture. No matter what the clones are all grass or all dirt. How do I go about having both textures randomly for the clones.
This is what I have tried when it is all grass or dirt.
public GameObject tile;
Texture2D[] textures = new Texture2D[2];
public Texture2D grass;
public Texture2D dirt;
// Use this for initialization
void Start () {
textures[0] = grass;
textures[1] = dirt;
tile.renderer.material.mainTexture = textures[Random.Range(0,1)];
Generation();
}
void Generation() {
for(int x = 0; x < 30; x++){
for(int y = 0; y < 2; y++) {
for(int z = 0; z < 30; z++) {
Instantiate(tile, new Vector3(x*1,y*Random.Range(0,2),z*1), Quaternion.identity);
}
Answer by rutter · Mar 20, 2012 at 06:44 AM
Take a look at what you're doing:
Create one object
Randomize its texture
Clone it many times
It's important to ask yourself: how many times do you want each of these steps to happen? Right now, you're only randomizing textures once. If you want to do so more than once, why isn't it done inside your spawn loop?
It sounds like you'd rather:
Create one object
Clone it many times
Randomize the texture of each clone
So this line in particular:
tile.renderer.material.mainTexture = textures[Random.Range(0,1)];
Remember that Instantiate()
returns a reference to the newly created object. You can use that reference to configure the object's renderer.
You could do something like this, for each copy you create:
var clone = Instantiate(...) as GameObject;
clone.renderer.material.mainTexture = textures[Random.Range(0,1)];
Your answer
![](https://koobas.hobune.stream/wayback/20220613065303im_/https://answers.unity.com/themes/thub/images/avi.jpg)