Skip to content

Instantly share code, notes, and snippets.

@0xdw
Created February 10, 2021 04:04
Show Gist options
  • Save 0xdw/982c0a60584600c5c6c28c31e7eb1405 to your computer and use it in GitHub Desktop.
Save 0xdw/982c0a60584600c5c6c28c31e7eb1405 to your computer and use it in GitHub Desktop.
Unity - Pick color in the screen point (x, y)
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
public class CheckPixelColor : MonoBehaviour {
private void Update() {
if (Input.GetMouseButtonDown(0)) {
if (EventSystem.current.IsPointerOverGameObject(-1) || EventSystem.current.IsPointerOverGameObject(0) ||
EventSystem.current.IsPointerOverGameObject(1)) {
return;
}
Vector3 pos = transform.position;
StartCoroutine(CheckColor((int) pos.x, (int) pos.y));
}
}
private IEnumerator CheckColor(int x, int y) {
Texture2D tex = new Texture2D(1, 1, TextureFormat.RGB24, false);
yield return new WaitForEndOfFrame();
tex.ReadPixels(new Rect(x, y, Screen.width, Screen.height), 0, 0, false);
tex.Apply(false);
RenderTexture currentRT = RenderTexture.active;
RenderTexture renderTexture = new RenderTexture(1, 1, 32);
Graphics.Blit(tex, renderTexture);
RenderTexture.active = renderTexture;
Color pixel = tex.GetPixel(x, y);
if (pixel.g == 0 && pixel.b == 0) {
// Black
} else {
// Some other color
}
RenderTexture.active = currentRT;
}
}
@0xdw
Copy link
Author

0xdw commented Feb 12, 2021

In 3D environments, I found this working.

private IEnumerator CheckColor() {
    Rect viewRect = Camera.main.pixelRect;
    Texture2D tex = new Texture2D((int) viewRect.width, (int) viewRect.height, TextureFormat.RGB24, false);

    yield return new WaitForEndOfFrame();

    tex.ReadPixels(viewRect, 0, 0, false);
    tex.Apply(false);

    // transform.position -> position you want to get the color
    Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
    Color pixel = tex.GetPixel((int) pos.x, (int) pos.y);
    if (pixel.g == 0 && pixel.b == 0) {
        // Black
    } else {
        // Some other color
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment