Change material in runtime
Okey, so I've been on this problem for ages now. I'm trying to change a material on my character in runtime, while playing. But everytime I change it by script, the 'starting material' that was originaly on the GameObject, get's instanced and it won't change to the new one I'm trying to put on it (see picture below).
I have to use .materials since it's Element 1 I want to change, and not Element 0, since using .material only changes Element 0.
I've tried to use 'sharedMaterials[1]' as well, nothing that helped.
public Material[] astronautMat;
public SkinnedMeshRenderer astronautRend;
void Start ()
{
astronautRend = GameObject.FindWithTag ("Astronaut").GetComponent<SkinnedMeshRenderer>();
}
void Update ()
{
AstronautMat ();
}
void AstronautMat()
{
if (Input.GetKeyDown (KeyCode.Keypad1))
{
astronautRend.materials[1] = astronautMat [0];
}
if (Input.GetKeyDown (KeyCode.Keypad2))
{
astronautRend.materials[1] = astronautMat [1];
}
}
Answer by jss1701 · Aug 17, 2017 at 12:34 AM
Same problem here. Could it be a problem in the current version?
found it!
You can't change just one element. You have to get the whole thing, change it, and assign it back.
Like this:
$$anonymous$$aterial[] mats = c.GetComponent().materials; mats[1] = fr; mats[2] = backing; c.GetComponent().materials = mats;