1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
[ExecuteInEditMode] [RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))] public class MyImage : MonoBehaviour { Mesh mesh; VertexHelper vertexHelper = new VertexHelper(); public Color color;
private MeshFilter meshFilter; private MeshRenderer meshRenderer; private MeshCollider collider;
public Texture2D texture; public Camera camera;
void Start() { meshFilter = GetComponent<MeshFilter>(); meshRenderer = GetComponent<MeshRenderer>(); collider = GetComponent<MeshCollider>(); camera = Camera.main; InitMesh(); }
void Update() { var ray = camera.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; Physics.Raycast(ray, out hitInfo); if (hitInfo.collider != null && hitInfo.collider.gameObject!=null) { if (Input.GetMouseButtonDown(0)) { Debug.Log("Image Clicked!"); } }
Debug.DrawLine(ray.origin, ray.origin + ray.direction*100, Color.red);
meshRenderer.material.color = color; meshRenderer.material.mainTexture = texture; }
private void InitMesh() { mesh = new Mesh(); vertexHelper.Clear(); vertexHelper.AddVert(new Vector2(0,0),color,new Vector2(0,0)); vertexHelper.AddVert(new Vector2(0,1),color,new Vector2(0,1)); vertexHelper.AddVert(new Vector2(1,1),color,new Vector2(1,1)); vertexHelper.AddVert(new Vector2(1,0),color,new Vector2(1,0));
vertexHelper.AddTriangle(0, 1, 2); vertexHelper.AddTriangle(2, 3, 0); vertexHelper.FillMesh(mesh);
meshFilter.mesh = mesh; collider.sharedMesh = mesh; }
}
|