Created
July 22, 2017 21:05
-
-
Save unity3dcollege/6156f4a6f48645fd6211185faa8126f2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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