I am creating a bit of an art program / game in Unity, however I need to create a color picker for the artists who are building things inside it. I am using the NGUI UI system, and I've created a basic sprite with a set of colors on it, along with a custom color input.
However, actually selecting one of those colors accurately is not proving easy. I'm currently doing it like this:
IEnumerator CaptureTempArea()
{
yield return new WaitForEndOfFrame();
tex = new Texture2D(Screen.width, Screen.height);
tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
tex.Apply();
Vector2 pos = UICamera.lastEventPosition;
int x = (int)pos.x;
int y = (int)pos.y;
Color color = tex.GetPixel(x, y);
Debug.Log(ColorToHex(color));
Debug.Log(tex.GetRawTextureData().Length / 1000);
Destroy(tex);
tex = null;
}
However, there must be a better way to capture -just- the specific area. This does accurately get the colors, however. But it also generates an image - even temporary - that is anywhere from 2 to 8 MB in size before it gets cleared from the buffer. Given the specific UI system, is there a better way to create a color picker, or one that will use less memory?
in general, I would optimize some stuff, like avoiding allocating/reading the while texture just to obtain a single pixel, and keeping a live 1x1 texture throughout the entire session... if your device support it you can also use computebuffer to pass the color value from a shader... this is how your code should look like (I haven't tested it, just rewritten your code a bit)
Texture2D tex;
void Start() {
tex = new Texture2D(1, 1);
//get the color printed by calling:
StartCoroutine(CaptureTempArea());
}
IEnumerator CaptureTempArea() {
yield return new WaitForEndOfFrame();
Vector2 pos = UICamera.lastEventPosition;
tex.ReadPixels(new Rect(pos.x, pos.y, 1, 1), 0, 0);
tex.Apply();
Color color = tex.GetPixel(0, 0);
Debug.Log(ColorToHex(color));
}
void OnDestroy() {
Destroy(tex);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.