Search Unity

Get Color from UI Image

Discussion in 'Scripting' started by Hapciupalit, May 28, 2015.

  1. Hapciupalit

    Hapciupalit

    Joined:
    Apr 24, 2015
    Posts:
    103
    So as we all know the UI Image has more components, but I need to acces the color of the Image and the Source Image from script so that i can change them . I tried with this script but it's not working.

    Code (JavaScript):
    1.  
    2.     var button = transform.Find("Button");
    3.     var buttonImage = background.GetComponent(UnityEngine.UI.Image);
    4.     print(buttonImage.color);
    5.     buttonImage.color = Color.red;
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    buttonImage.sprite.texture.getpixel(1, 1)

    might be 0,0 :)
     
  3. Hapciupalit

    Hapciupalit

    Joined:
    Apr 24, 2015
    Posts:
    103
    Thanks but it's not working
     
  4. Todd-Wasson

    Todd-Wasson

    Joined:
    Aug 7, 2014
    Posts:
    1,079
    Here's how I'm doing it:

    Code (csharp):
    1.  
    2. void Update()
    3.     {
    4.         Vector2 localPoint = Vector2.zero;
    5.        
    6.         if (GameManager.riftMode)
    7.         {
    8.             screenPoint = cam.WorldToScreenPoint(vrCursor.transform.position);
    9.         }
    10.         else
    11.         {
    12.             screenPoint = Input.mousePosition;
    13.         }
    14.  
    15.         RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPoint, cam, out localPoint);
    16.  
    17.         rectTransform.GetLocalCorners(localCorners);
    18.         imgWidth = localCorners[3].x - localCorners[0].x;
    19.         imgHeight = localCorners[1].y - localCorners[0].y;
    20.  
    21.         Vector2 positionNormalizedForTexCoords;
    22.         positionNormalizedForTexCoords.x = localPoint.x / imgWidth + 0.5f;
    23.         positionNormalizedForTexCoords.y = localPoint.y / imgHeight + 0.5f;
    24.  
    25.         if (Input.GetMouseButton(0))
    26.         {
    27.             if (positionNormalizedForTexCoords.x >= 0 && positionNormalizedForTexCoords.x <= 1 &&
    28.                 positionNormalizedForTexCoords.y >= 0 && positionNormalizedForTexCoords.y <= 1)
    29.             {
    30.                     pickedColor = tex.GetPixelBilinear(positionNormalizedForTexCoords.x, positionNormalizedForTexCoords.y);
    31.                     //print(positionNormalizedForTexCoords + "   pickedColor " + pickedColor);
    32.                     UpdatePickedColorGameObject(pickedColor);
    33.             }
    34.         }
    35.        
    36.     }
    37.  
    38.     void UpdatePickedColorGameObject(Color color)
    39.     {
    40.         Image img = pickedColorGameObject.GetComponent<Image>();
    41.         img.color = color;
    42.     }
    43.  
     
    Olipool likes this.