- Home /
type ...Material[] vs Material (materials change at run time)
I am trying to look through an array of materials on a specific game object and change the material at run time. I have read over multiple pages of the scripting reference on materials, game objects, render, transforms, Material.SetTexture and so on. I have also searched and read others answers on similar questions in the forums. All this research points to the fact that I should be using material[] to form an array which will allow me to set the material element I need to change.
However using the code below I get this: error CS0029: Cannot implicitly convert type UnityEngine.Material' to
UnityEngine.Material[]'
I can not find a resolution for this error and I'm not sure how to convert the material to an array.
What am I doing wrong with my code?
using UnityEngine;
using System.Collections;
public class ChangeMaterial : MonoBehaviour {
//Put the game object with the texture you are changing here.
GameObject Model;
public string target;
// put the first material here.
public Material material1;
// put the second material here.
public Material material2;
bool FirstMaterial = true;
bool SecondndMaterial = false;
Material[] themes;
void Start ()
{
Model = GameObject.Find (target);
themes = Model.renderer.materials[4];
themes[4] = material1;
Model.renderer.materials[4] = themes;
}
void OnMouseDown()
{
if (!SecondndMaterial)
{
themes[4] = material2;
SecondndMaterial = true;
FirstMaterial = false;
}
else if (SecondndMaterial)
{
themes[4] = material1;
FirstMaterial = true;
SecondndMaterial = false;
}
}
}
P.S. if you use
$$anonymous$$odel.renderer.material[4]
ins$$anonymous$$d of
$$anonymous$$odel.renderer.materials[4]
the lack of an s changes the error to: error CS0021: Cannot apply indexing with [] to an expression of type `UnityEngine.$$anonymous$$aterial'
The problem is mixing class instance with array of class instances. I suggest reading a short info on arrays in Unity Wiki. If, after reading it, you'll still have problem, please return here.
Answer by zertach · Nov 07, 2013 at 10:36 PM
Model = GameObject.Find(target);
themes = Model.renderer.materials[4];
themes[4] = material1;
Model.renderer.materials[4] = themes;
themes is array and materials[4] returning single material. so you can not transfer single material to material array.
delete all those lines and use like this. Model.renderer.materials[4] = yournewmaterial
This still is not working for me. Can the "yournewmaterial" be set with material1 and material2 in my code? I'm not getting an error in the console but the material does not change.