EB25BALL Spark
EB25BALL Spark

Reputation: 44

how do I set a color to a spefic/certain buttons in unity

I have a ButtonManger.cs file which takes an array of buttons. I want to know how I can change all the buttons colors by the empty object(My ButtonManger Object). so basically once a button(that is in the array) is trigged/clicked it will tell the buttonmanger to change the color of the buttons(in array).

using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ButtonManger : MonoBehaviour
{

   public Button[] button;

   public string selectedButton { get; private set; }

   private void Awake()
   {
       button = FindObjectsOfType<Button>();
       selectedButton = EventSystem.current.currentSelectedGameObject.name;
   }
   public void OnClickedButton()
   {
     
           GetComponents<Button>().material.color = new Color(0.3f, 0.4f, 0.6f, 0.3f); 
//this is where I cant get it to work, getComponents<Button>().material doesnt work
 
   }
}```

Upvotes: 0

Views: 313

Answers (2)

Vlad Stoyanoff
Vlad Stoyanoff

Reputation: 163

This does the job for me:

using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;

public class ChangeButtonColor : MonoBehaviour
{
    Button[] buttonsArray;

    void Awake()
    {
        buttonsArray = FindObjectsOfType<Button>();
    }

    public void ChangeButtonColors()
    {
        var newColor = Color.blue;

        for (int i = 0; i < buttonsArray.Length; i++)
        {
            buttonsArray[i].GetComponent<Image>().color = newColor;
        }
    }
}

Change the color to your preferences on the first line of code under the ChangeButtonColor method.

Go to your buttons that and attach this method to whatever buttons you want.

enter image description here

Let me know if you have any other questions.

Vlad

Upvotes: 2

mrpigus
mrpigus

Reputation: 21

Material color can be set with: https://docs.unity3d.com/ScriptReference/Material.SetColor.html

Keep in mind that your material can have multiple colors based on the used shader. Default is _Color. I also recommend setting Color to public space so you can easily adjust it in the Inspector.

       public Color color_buttonpressed;
       public void OnClickedButton()
       {
               GetComponents<Button>().material.SetColor("_Color",color_buttonpressed);
       }

Upvotes: 0

Related Questions