Search code examples
c#unity-game-enginecolorspanel

unity how to changing panel color when click button


i want to Change panel color when i click button , i try with code its change button color not panel color

public Image panel;
  // Use this for initialization
  void Start () {
      panel = GetComponent<Image>();
  }

  // Update is called once per frame
 public void OnButtonClick {


      panel.color = GetRandomColor();

  }
  Color GetRandomColor(){

      return new Color(Random.value, Random.value, Random.value);
  }

} 

What do I need to do?


Solution

  • Ah, what the heck, I will explain why it's not working and what you should do.

    (I assume you changed Update method as I suggested in comments)

    First of all you should check to what GameObject your script is attached in the Editor. I assume it is attached to the Button. So what is happening in the Start method? Right — you are assigning Image component of the Button to panel variable. So when panel.color = GetRandomColor(); is called it changes color of the Image component of the Button.

    What can you do about this? Simple way would be to remove Start method completely and since panel variable is declared as public assign it to panel GameObject in the Editor.