- Home /
Changing material depending on variable
I have an object that I am trying to change the material depending on a user decided variable. I am trying to change what material a variable references during runtime (eg., player sets the variable to 3 and it will find the Material named 3 and assign it to flagMat. Is there any way to do this? I don't really want to type out nearly 200 if statements.
Answer by robertbu · Apr 23, 2013 at 04:45 AM
An easy way to deal with a list of materials is to use an array. Here is a sample script that uses an array of materials and randomly changes the material each time the space bar is pressed:
#pragma strict
var materials : Material[];
function Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
renderer.material = materials[Random.Range(0,materials.Length)];
}
}
You would initialize materials in the inspector. Click on the arrow next to the 'materials' variable, set the size of the array then drag and drop the materials into the array. You can instead load the materials array using Resources.Load().
Note given that you are going to have 200 materials, I have to wonder how the materials differ. If it is only a texture or color, it might be easier/better to keep a single material and just set a new texture/color for the material.
It's a cloth that will have every countries flag, so I can't just change the colour unfortunately. But I guess if I just have to assign each flag in the inspector thats better than a bunch of ifs. I have another variable flagNum that gets changed by the player (pressing [ subtracts 1, pressing ] adds 1) and I have the flag materials named 1, 2, 3, etc. I was hoping there was some way that I could first assign flag$$anonymous$$at to a material depending on that variable, then set renderer.material to flag$$anonymous$$at.
You can select all the materials and drag them onto the materials array at once (use the lock icon in the inspector). It doesn't matter what they are named; you just use a number to refer to them in the order they are listed in the array. So it would be better to use more descriptive names ins$$anonymous$$d of "1", "2", etc.
If all that changes is the texture (bitmap), then you don't need to change the material for each flag...just change the texture. You can create a texture array similar to the materials array in the example above, or you could dynamically load the flag you want Resources.
Okay I thought I would have to add each flag individually to the array. But I guess if I can drag them all at once, that's perfect! And robertbu, I'm using materials not textures.
Answer by Bunny83 · Apr 23, 2013 at 03:15 PM
Another way which is usually easier is to use one flag atlas like this one and adjust the uv coords of your mesh. However in any case you have to define in which order they are so you can find the right one.
If you use an array like robertbu mentioned, add them in this order: SystemLanguage. That way you can use Application.systemLanguage directly as index ;)