- Home /
Object Material change with script and a button?
I'm currently using this code so far :
//Change renderer's material each changeInterval
// seconds from the material array defined in the inspector.
var materials : Material[];
var changeInterval = 0.33;
function Update () {
if (materials.Length == 0) // do nothing if no materials
return;
// material index
var index : int = Time.time / changeInterval;
// take a modulo with materials count so that animation repeats
index = index % materials.Length;
// assign it to the renderer
renderer.sharedMaterial = materials[index];
}
( Found from Unity Script Reference Help )
and it's working for switching the materials on my plane by a timer. I would like to know if there is a way to make this better by making the materials switch with a button such as a Mouse click or just a button press. Even better would be to figure out a way to click on a made button in the game for the "next material" button.
The furthest I figure is somehow making a counter.
Please help!
O$$anonymous$$, to make this simpler, since I don't want to use a Gui....if I use a Input.Get$$anonymous$$eyDown button ins$$anonymous$$d...how would I make that??
Something like ..?
function Update() { if(Input.Get$$anonymous$$eyDown("a").Button, "Next $$anonymous$$aterial:)?
Answer by JesusChristChangedMe · Nov 12, 2010 at 02:06 AM
i see what you want. ok, here is a script to say that when spacebar is hit to change the material next in the index. if you would like it to be left mouse click then use Fire1 instead of Jump in the script.
var myMaterials : Material[]; var NextMaterial : int = 0; function NextMaterialUsed() { renderer.sharedMaterial = myMaterials[NextMaterial]; if(NextMaterial < myMaterials.length-1) NextMaterial += 1; else NextMaterial = 0; }
function Update () { if(Input.GetButtonDown("Jump")) { NextMaterialUsed(); }
}
hope this help out!
Doesn't seem to work for me. I'm trying to avoid GUI's as much as possible since I have no idea how to use them.
hmm... well i tired the script on a simple box i made and it worked fine. the only thing i can think of is if you didnt add the script to the object you want to change or you forgot to make the size number bigger under the script component and add new materials to it.
and if you wanted to change the color by pressing spacebar then you could do if(Input.GetButtonDown("Jump")) { //here you tell it to go to the next material. }
ill change my answer to fit what you want.
I managed to fix it the way I wanted a couple of days ago. Thanks for your help though, you got me most of the way. :)
Answer by javim93 · Feb 12, 2014 at 01:35 AM
How can i use the script to change the material of only one object. I have repeated the same object many times in scene, and pushing the button makes all the objects to change material.
Answer by cadviz · Sep 15, 2012 at 04:31 AM
Hi I hope this may help
http://www.burgzergarcade.com/tutorials/c/dynamically-changing-materials-unity