- Home /
how to switch material with script?
I want to do something like if material on that gameObject is matA switch it to matB and if it has matB switch it to matA, while
Debug.Log(this.GetComponent<Renderer>().material.name);
does return name of material on that gameObject, but
if (this.GetComponent<Renderer>().material.name == "MatA")
{
Debug.Log("reached here");
}
doesnt return anything(it doesnt reach there even though gameObject has MatA), how come ?
also, what do I write inside if() statement to switch color to MatB ?
EDIT : -
if (this.GetComponent<Renderer>().sharedMaterial.name == "MatA")
{
Debug.Log("reached here");
}
it does reach here now, if I change material to sharedMaterial.
but I dont know what do I put inside if statement to find material and assign it to this.gameObject ?
thanks in advanced
Answer by Ambrose998800 · Jan 02, 2019 at 05:42 PM
Try not to reference by name:
public Material MatA;
public Material MatB;
void ChangeMat()
{
Material CurrentMat = gameObject.getComponent<Renderer>().material;
if (CurrentMat == MatA)
{
CurrentMat = MatB;
}
else if (CurrentMat == MatB)
{
CurrentMat = MatA;
}
}
hi, thanks for the reply,
unfortunately, it doesnt work. I dont know whats wrong, it look like it should work, it doesnt even show any error.
Try calling the shared$$anonymous$$aterial
$$anonymous$$aterial Current$$anonymous$$at = gameObject.getComponent<Renderer>().shared$$anonymous$$aterial;
still doesnt work. plus while we are at it, how do I find material so I dont have to assign them manually in
public $$anonymous$$aterial $$anonymous$$atA;