Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created July 22, 2017 21:05
Show Gist options
  • Save unity3dcollege/6156f4a6f48645fd6211185faa8126f2 to your computer and use it in GitHub Desktop.
Save unity3dcollege/6156f4a6f48645fd6211185faa8126f2 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class ColorPicker : MonoBehaviour
{
public static Color SelectedColor { get; private set; }
[SerializeField]
private Renderer selectedColorPreview;
private void Update()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var picker = hit.collider.GetComponent<ColorPicker>();
if (picker != null)
{
Renderer rend = hit.transform.GetComponent<Renderer>();
MeshCollider meshCollider = hit.collider as MeshCollider;
if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
return;
Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
SelectedColor = tex.GetPixel((int)pixelUV.x, (int)pixelUV.y);
selectedColorPreview.material.color = SelectedColor;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment