How would I change a gameObject's material via scripting?
3 Answers
3First 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
– MrPhilUse:
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.
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.
– anon78673258OK, let’s say we want to change the color of the material of current game object which this script attached to ![]()
all you need is this line ![]()
GetComponent<Renderer>().material.color = Color.cyan;
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
– Gruffy> 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
– Lo0NuhtiK