batch textures, shared materials, instantiation, sharedmaterial array

how do you batch textures on game objects in JavaScript? say you have GameObject cubePrefab and 9 textures to apply to it as shared material-

this took me about 4 hours to find out as i am noob, I couldn’t seem to find an answer for it and it’s pretty unintuitive so here goes:

declare global variables

    var mymaterials = new Material[9];
    var sw1 : UnityEngine.Texture;//do this for 9 textures

in start function fill the multi-material array with different materials and give them the texture:

var mat1 = cubePrefab.renderer.material;
mymaterials[0] = cubePrefab.renderer.material;
mymaterials[1] = new Material(mat1);
mymaterials[2] = new Material(mat1);
mymaterials[3] = new Material(mat1);
mymaterials[4] = new Material(mat1);
mymaterials[5] = new Material(mat1);
mymaterials[6] = new Material(mat1);
mymaterials[7] = new Material(mat1);
mymaterials[8] = new Material(mat1);

mymaterials[0].mainTexture = sw1;
mymaterials[1].mainTexture = su1;
mymaterials[2].mainTexture = sd1;
mymaterials[3].mainTexture = sw2;
mymaterials[4].mainTexture = su2;
mymaterials[5].mainTexture = sd2;
mymaterials[6].mainTexture = sw3;
mymaterials[7].mainTexture = su3;
mymaterials[8].mainTexture = sd3;

that’s all you have to do! Afterwards, when you have a an instantiated prefab and you want to apply different batched textures to it do-

stpc.renderer.material = mymaterials[1];
stpc.renderer.material = mymaterials[9];

EDIT- draw calls 10, batched 468, FPS=120 :smiley: