- Home /
Change texture of gameobject in array.
I finally got my texture to work but now i want to be able to change it to a other texture. I know how to do it on a single object, but now i want to try and change it while the object is in a array.
var cubeZero : GameObject;
var cubes : GameObject[,] = new GameObject[9,9];
var RedColorTex:Texture2D;
var BlueColorTex:Texture2D;
function Start () {
cubeZero = Resources.Load("Cube");
for(x=0; x<9; x++){
for(y=0; y<9; y++){
var r : GameObject = Instantiate(cubeZero, transform.position, Quaternion.identity);
r.renderer.material.mainTexture= BlueColorTex;
cubes[x,y] = (r.gameObject);
r.transform.position = Vector3(x+0.5,y+0.5,0.5);
cubes[5,5].renderer.material.mainTexture= RedColorTex;
}
}
}
This line gives a error. cubes[5,5].renderer.material.mainTexture= RedColorTex; But i was wondering if it is possible. I know this array type ain't a easy one to use because you can't alter much in it.
Answer by robertbu · Jul 02, 2013 at 03:32 PM
You should use #pragma strict on your scripts. You are missing your 'var' in your 'for()' loops. But this is not the issue that is causing you the problem. The issue is that you are trying to set Cubes[5,5] in the inner loop of your nested 'for()' loop. That is, entry [5,5] has has not been created and filled by your 'for()' loop when you try to access that entry. Move setting the texture to after the 'for()' loops:
#pragma strict
var cubeZero : GameObject;
var cubes : GameObject[,] = new GameObject[9,9];
var RedColorTex:Texture2D;
var BlueColorTex:Texture2D;
function Start () {
cubeZero = Resources.Load("Cube");
for(var x=0; x<9; x++){
for(var y=0; y<9; y++){
Debug.Log(x+","+y);
var r : GameObject = Instantiate(cubeZero, transform.position, Quaternion.identity);
r.renderer.material.mainTexture= BlueColorTex;
cubes[x,y] = (r.gameObject);
r.transform.position = Vector3(x+0.5,y+0.5,0.5);
}
}
cubes[5,5].renderer.material.mainTexture= RedColorTex;
}
Or if you are trying to set the colors as you go, use 'x' and 'y':
if (x / 2 * 2 == x)
cubes[x,y].renderer.material.mainTexture = RedColorText;
This will set all the cubes in which 'x' is even to the 'RedcolorText'.
Ooh how stupid of me, your totally right. (before this problem i was trying to make texture work and i accidentally put the line in the loop) Thanks for the help
Your answer
Follow this Question
Related Questions
changing the tags in an array 1 Answer
How do I keep a texture different on copied objects? 1 Answer
Array like level system to change rules. 1 Answer
Best option to change texture/material.. 0 Answers
Spell-casting combo system 1 Answer