- Home /
Help Changing Materials On Button Click
Here is the script I am using to select objects, but in the "function manipulateChosenTransform ()", it works great for object selection, but isn't playing nice to change materials. What I am trying to do is if an object is currently selected, I want it's material to change from a diffuse to a diffuse transparent so only the selected objects opacity can be messed with by a slider. But once you select another object, the previously selected object goes back to it's difuse material. Any help is much appreciated.
var hSliderValue : float = 1.0;
var opacityText : GUIStyle;
var arrayOfTransforms : Transform [];
var guiRectangle : Rect = Rect(200, 200, 300, 300);
var chosenTransform : Transform;
var originalMaterial : Material;
var replaceMe : Material;
function OnGUI ()
{
/* make sure the array isn't null or empty */
if ( ! arrayOfTransforms || arrayOfTransforms.length == 0 ) {
Debug.LogError("Please initialize array of transforms...");
return;
}
GUILayout.BeginArea(guiRectangle);
for ( var i = 0; i < arrayOfTransforms.length; i ++ ) {
/* use a variable to keep track of the current Transform */
var thisTransform = arrayOfTransforms[i];
/* draw a button for each item in the array */
if ( GUILayout.Button("Choose " + thisTransform.name) ) {
/* if the button is pressed, store the current transform */
chosenTransform = thisTransform;
}
}
GUILayout.Box("You have chosen: " + chosenTransform.name);
GUILayout.EndArea();
getValue();
hSliderValue = GUI.HorizontalSlider (Rect (110, 325, 150, 30), chosenTransform.renderer.material.color.a, 0.0, 1.0);
GUI.Label (Rect (55, 323, 100, 20), "Opacity", opacityText);
manipulateChosenTransform ();
}
function getValue()
{
return hSliderValue;
}
function changeTexture() {
chosenTransform.renderer.material= replaceMe;
}
function changeTextureToNormal() {
chosenTransform.renderer.material= originalMaterial;
}
function manipulateChosenTransform ()
{
if ( ! chosenTransform ) {
return;
}
}
if (chosenTransform) {
changeTexture();
}
else changeTextureToNormal();
print("You have chosen to do something to " + chosenTransform.name);
print("Here is its current position: " + chosenTransform.position);
chosenTransform.renderer.material.color.a = hSliderValue;
function Awake ()
{
if ( ! arrayOfTransforms || arrayOfTransforms.length == 0 ) {
Debug.LogError("Please initialize array of transforms...");
return;
}
chosenTransform = arrayOfTransforms[0];
}