Unity 2D : Get pixel of color of Raw Image

7.4k views Asked by At

I want to know how I can get the pixel color of my rawImage texture.

This is my scene:

enter image description here

public class ColorPicker : MonoBehaviour, IPointerClickHandler
{
    public GameObject Cube;

    public void OnPointerClick(PointerEventData eventData)
    {
        if (Input.GetMouseButtonUp(1))
        {
            Vector3 localPosition = transform.InverseTransformPoint(eventData.pressPosition);

            Color color = (GetComponent<RawImage>().texture as Texture2D).GetPixel(Convert.ToInt32(localPosition.x),
               Convert.ToInt32(localPosition.y));
            Cube.GetComponent<Renderer>().material.color = color;
        }
    }
}

And as you can see, with this code, it work but it is not scalled.

In fact, I can't reach the blue color. I only can get the top of my square.

Can you help me how to get the color when I press the right click ?

Thanks

2

There are 2 answers

1
Commodore Yournero On

The mouse position you get using

Input.mousePosition 

is in screen space (meaning the position you get is relative to the screen size).

What you want to get is the mouse position in canvas space (relative to the canvas size, so you don't have to worry about the canvas size).

You can do this by implementing IPointerClickHandler in your ColorPicker script (which is also better practise than using Input.mousePosition).

using UnityEngine.EventSystems;    

  public class ColorPicker : MonoBehaviour, IPointerClickHandler{

  public GameObject Cube;

  void OnPointerClick(PointerEventData eventData)
  {
     //eventData.position
     //Vector3 localPosition = transform.InverseTransformPoint(eventData.pressPosition);
     //ignore z coordinate
  }
}

The PointerEventData contains a lot of useful information, you can get more information in the unity documentation https://docs.unity3d.com/ScriptReference/EventSystems.PointerEventData.html

You probably still need to convert your mouse position using

transform.InverseTransformPoint(eventData.pressPosition);

as i have not tested this yet. But i hope this points you in the right direction!

0
Helios Cubing On

Try converting it into a 2DTexture, then you can use the Texture2D.GetPixels function.