/* 獲取模型對應的貼圖中的像素點,修改顏色 */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class DrowLine : MonoBehaviour { public GameObject m_obj; private Texture2D m_tex; public Color m_color; public int size = 3; private Color[] m_textureColorsStart; void Start () { m_tex = m_obj.GetComponent<MeshRenderer>().material.mainTexture as Texture2D; //從紋理中獲取像素顏色 m_textureColorsStart = m_tex.GetPixels(); Debug.Log(m_tex.name); } void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Input.GetMouseButton(0)) { if (Physics.Raycast(ray, out hit)) { //在碰撞位置處的UV紋理坐標。 Vector2 pixelUV = hit.textureCoord; //以像素為單位的紋理寬度 pixelUV.x *= m_tex.width; pixelUV.y *= m_tex.height; //貼圖UV坐標以右上角為原點 for (float i = pixelUV.x - 1; i < pixelUV.x + size; i++) { for (float j = pixelUV.y - 1; j < pixelUV.y + size; j++) { m_tex.SetPixel((int)i, (int)j, m_color); } } Debug.Log(pixelUV); m_tex.Apply(); } } if (Input.GetKeyDown(KeyCode.Escape)) { //還原 m_tex.SetPixels(m_textureColorsStart); m_tex.Apply(); } //在處理鼠標按下的記錄下位置,抬起的時候記錄下位置,取2個位置中間的位置發射射線 //if (Input.GetMouseButtonDown(0)) //{ //} //if (Input.GetMouseButtonUp(0)) //{ //} } }