- Home /
How do I get a material from a GameObject?
I have a bunch of cubes that I instantiate with different materials using an ID system. The array of materials is set up like so:
var materialList : Material[]; var mat0 : Material; var mat1 : Material; var mat2 : Material; var mat3 : Material;
function LoadMaterials() { materialList = new Material[3]; materialList[0] = mat0; materialList[1] = mat1; materialList[2] = mat2; }
When I create the cubes I do so like this:
var cube = Instantiate(smallCube, Vector3 (x, z, y), Quaternion.identity);
cube.renderer.material = materialList[textureId];
Now with another function I am iterating through all of the cubes to get the x, y, and z positions, but I want to also get the texture. If I can figure out the texture from just the gameobject then I want to do that so I don't have to store that information separately. If I do have to store the information some how can i store it with the gameobject itself? Here is an example to show what i mean:
cubes = GameObject.FindGameObjectsWithTag("cube"); for(var cube : GameObject in cubes) { cubeX = cube.transform.position.x - lowX; cubeY = cube.transform.position.y - lowY; cubeZ = cube.transform.position.z - lowZ;
textureId = ?????;
}
If there isnt some function that lets me get the material name to a string from the gameobject then can I do something like cube.MyVar? Thanks for any help!
Answer by Eric5h5 · Jan 22, 2011 at 06:00 PM
You can replace this:
var materialList : Material[];
var mat0 : Material;
var mat1 : Material;
// etc, etc
with this:
var materialList : Material[];
You don't need the rest of that; the point of arrays is that you don't use individual variables.
As for the texture, probably the easiest way is to store the texture number in a component in the prefab. The component can just be a script called "ID" that says
var textureId : int;
When instantiating, you can do
cube.GetComponent(ID).textureId = textureId;
Then to get the ID later, you can do
textureID = cube.GetComponent(ID).textureId;
But without
var mat0 : $$anonymous$$aterial;
//etc
I cant drag references to the materials, right?
Of course you can; just add as many array entries as you need.
Ah thanks! I see where i was going wrong, have to set the size and pull down the array on the inspector.