There is a lot of material on these forums about how to detect mouse presses on collision meshes, but I’ve been unable to adapt other user’s solutions for my own situation.
I dynamically create a game object at run time and give it a mesh (the meshes have come from an xml file and are just simple 2D flat polygons at y=0. There’s very little overlap (if any) between polygons).
So I have something like this when I parse in the xml file.
/
// Create the rendered mesh for the Game Object
//
Mesh mesh = new Mesh();
mesh.vertices = verticesTemp.ToArray();
mesh.colors = colors;
mesh.triangles = triangles;
//
// Dynamically create the GameObject and add the required components
//
GameObject gameObj = new GameObject(building.name);
gameObj.AddComponent("MeshFilter");
gameObj.AddComponent("MeshRenderer");
gameObj.AddComponent ("MouseHandler"); // Used for mouse events
gameObj.AddComponent("MeshCollider");
gameObj.renderer.material.shader = Shader.Find("PlainColorShader");
gameObj.GetComponent<MeshFilter>().mesh = mesh;
//
// Create a collision mesh (it's the same data as the rendered mesh)
//
Mesh collisionMesh = new Mesh();
collisionMesh.vertices = verticesTemp.ToArray();
collisionMesh.triangles = triangles;
MeshCollider meshCollider = gameObj.GetComponent<MeshCollider>();
meshCollider.sharedMesh = collisionMesh;
As a result, I have many GameObjects in the hierarchy and selecting each shows an attached Mesh Collider and Mouse Handler component (amongst other things)
When in Scene mode, I can see the green wireframe representing the collision mesh, but I can’t seem to be able to mouse click it using my MouseHander script/component that I’ve dynamically added to the GameObject.
I’ve tried casting rays upon mouse press inside the update() method…
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) {
Debug.Log("hit");
}
}
}
…and I’ve also tried to use the OnMouseOver() method…
void OnMouseOver() {
if (Input.GetMouseButtonDown(0)) {
Debug.Log("hit");
}
}
Does anyone have any ideas why this might not be working?
Thanks.