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.

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.

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 :wink: