How to change a gameObject's material via scripting?

How would I change a gameObject's material via scripting?

Hey bud, here is a link to an answer with the same issue as your, I answered it about a week ago. [LinkToAnswer][1] Take the zip on the page and download , extract the package and import it, then have a peek at whats going on in de code. Take care bud. Gruffy [1]: http://answers.unity3d.com/questions/676243/3d-text-as-a-button-1.html

> Hey bud, here is a link to an answer with the same issue as your, I answered it about a week ago. @Gruffy : Did you notice this topic was created back in 2010? xD

3 Answers

3

First of all, a GameObject can't have a material. It can, however, have a Renderer, which has a Material: http://unity3d.com/support/documentation/ScriptReference/Renderer-material.html

So basically:

renderer.material = myOtherMaterial;

Be careful, renderer.material clones the material and this can causes a memory leak. "If the material is used by any other renderers, this will clone the shared material and start using it from now on." [http://docs.unity3d.com/ScriptReference/Renderer-material.html][1] [1]: http://docs.unity3d.com/ScriptReference/Renderer-material.html

Use:

var texture : Texture;

function Start () {
    renderer.material.mainTexture = texture;
}

To change the texture to the material exposed in the inspector. For further material and texture documentation follow this link.

That doesn't really change the material.

What do you mean? It's from the docs.

I guess it depends on what you mean by change. My understanding of the question was that the author wanted to exchange the material, not just modify it.

I think he just wanted to have a different texture.

Ya. thanks to both of you guys. sorry I didn't write my question clearly.

OK, let’s say we want to change the color of the material of current game object which this script attached to :slight_smile:
all you need is this line :slight_smile:

GetComponent<Renderer>().material.color = Color.cyan;