- Home /
Get color of button and set to an object
I am new to scripting and need some help. What I have on my scene is several buttons of many different colors. I also have an object with a material on it. How would I go about making the albedo color of my object be set to the color of the button that is pressed? (I would like it so that if I pressed the red button the object would change to red) Is there a way that I could get the color of the button that got pressed and then set that color to be the albedo of my object? I don't know exactly how to write it but this is how I picture it would look in scripting: objectAlbedoColor=getColor(button);
Answer by zachwuzhere · Oct 26, 2017 at 11:51 PM
something like this?
Button mybutton;
GameObject myGameObject;
void MyButtonClickFunction(){
//Get the color from you buttons material component
Vector4 myButtonsColor = mybutton.GetComponent<Material>().color;
/*Get the material component from your game object
and set its color to the new color defined above*/
myGameObject.GetComponent<Material>().color = myButtonsColor;
}
I got it set up but I am getting an error: $$anonymous$$issingComponentException: There is no $$anonymous$$aterial attached to the "Button" game object but a script is trying to access it. The color of the button is in the Image section of the button. (Right under source image). I do not have a material assigned to the button. Thanks for your help.
If you need to get the color from the image of your button then try this... Vector4 myButtonsColor = mybutton.image.color;
I got it working! YAY! Here is the code with some edits. (because for some reason it told me that my object didn't have a material even though it clearly did) using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class ButtonColor : $$anonymous$$onoBehaviour {
public Button mybutton;
public GameObject myGameObject;
public void $$anonymous$$yButtonClickFunction()
{
//Get the color from you buttons material component
Vector4 myButtonsColor = mybutton.image.color;
/*Get the material component from your game object
and set its color to the new color defined above*/
myGameObject.GetComponent<Renderer>().material.SetColor("_Color", myButtonsColor);
}
}
Your answer
Follow this Question
Related Questions
Image UI color not changing when sprite is set via script 0 Answers
how to change color in unity scripting overtime?,how to change color gradually with C# 2 Answers
Color of some instantiated objects differs from the normal ones. 1 Answer
Changing the color of individual particles 0 Answers
Button image sprite colour change 1 Answer