Search Unity

Changing the color of a panel in code

Discussion in 'Unity UI (uGUI) & TextMesh Pro' started by jbjbjbborisb, Dec 17, 2014.

  1. jbjbjbborisb

    jbjbjbborisb

    Joined:
    Jun 8, 2014
    Posts:
    54
    Hi,
    how can I change the color of a panel in code?
    I can't find a way to get to the panel's color property :-(
     
  2. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,140
    a panel is mainly just a image. you just need to change the image color.
     
  3. jbjbjbborisb

    jbjbjbborisb

    Joined:
    Jun 8, 2014
    Posts:
    54
    Thanks for your reply.
    I tried to access the color via this.image.color = ..., but the panel does not have a image property.

    Ho else would I gain access to the image?
    Could you provide me with a code snippet?
     
  4. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,140
    I'm confused. There is no panel script as part of the UI system so i dont know where you'd be doing a this.image.color. Image is a component so you'd need to get that component from the panel GO.
     
  5. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    jbjbbborisb, gameObjects don't have an already defined property for Image. You have to fetch it yourself, like this:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public class PanelColorer : MonoBehaviour {
    6.  
    7.     Image panel;
    8.  
    9.     void Start(){
    10.         //Right here. Make sure there's an image component attached,
    11.         //or it will throw an error in Update()
    12.         panel = GetComponent<Image>();
    13.     }
    14.  
    15.     void Update(){
    16.         panel.color = GetRandomColor();
    17.     }
    18.  
    19.     Color GetRandomColor(){
    20.         return new Color(Random.value, Random.value, Random.value);
    21.     }
    22.  
    23. }
    24.  
     
    Ylex likes this.