Created
February 10, 2021 04:04
-
-
Save 0xdw/982c0a60584600c5c6c28c31e7eb1405 to your computer and use it in GitHub Desktop.
Unity - Pick color in the screen point (x, y)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In 3D environments, I found this working.