Change Object color with GUI buttons

Hi !

I´ve run into the following problem:
I want to have several buttons in my GUI to switch colors of components of my object.

I´ve found the following code and have applied it to the components of my object that I want to change.

var colorStart = Color.blue;
var colorEnd = Color.green;
var duration = 10.0;

function Update () {
var lerp = Mathf.PingPong (Time.time, duration) / duration;
renderer.material.color = Color.Lerp (colorStart, colorEnd, lerp);
}

Now my questions:

How can I transform the above script to check the current color of the compnent before lerping to the desired colour ?

Can I somehow apply the change of colour with the script to all components in question, or do I have to apply it manually to every component ?

Finally, how do I attach the script to a GUI Button ?

Is there somewhere a piece of code around that would help me with this ?

Thx.

Add an if statement:

function Update () {
  if (renderer.material.color == colorStart) {
    ...
  } else if (renderer.material.color == colorEnd) {
    ...
  } else {
    ...
  }
}

It’s not clear exactly what you’re after but if…else blocks are the way to check for a condition and respond as desired.

What do you mean by “apply the change … to all components in question”? There is only one renderer attached to each game object so you won’t be manipulating more than one of those at a time.

You don’t “attach scripts to a button” with Unity’s GUI system as the buttons/UI elements aren’t objects in specific. Instead you would have an OnGUI function that draws your button, and when pressed it can call a helper function to initiate whatever behavior you like:

function OnGUI () {
  if (GUI.Button(Rect(5,5,60,20), "Press Me")) {
    DoSomething();
  }
}

function DoSomething () {
  // insert code here to trigger whatever
}

Check out the GUI Scripting Guide for more information.

That’s hard to answer as your ultimate goal isn’t really clear, but I sense not. In any case give the above information a look and let us know if you have any follow-up questions!