- Home /
OnMouseDown with two camera, how can I make it work?
I have an object, this object is just a box, with a box collider and a rigidbody. Attached to the cube there is a simple script
function OnMouseDown() { Debug.Log("I'm working"); // code }
however when I click on the cube I don't see the message. I make some research and I discovered that OnMouseDown is not working well when there are two camera in the scene.
I have two camera; the first one is the main camera and is attached to the first person controller, the second one is a text camera.
Depth only HUD Text Orthographic
this problem is creating a lot of issue. I don't know hot to solve it; there is anyone with some idea ?
Answer by robertbu · Jun 06, 2013 at 03:40 AM
One way to solve the issue is to go from OnMouseDown() to using Raycasting to detect a hit. It is hard for me to suggest specifics with so little knowledge of what you do inside your OnMouseDown(). The typical structure would be:
function Update() {
if (Input.GetMouseButtonDown(0)) {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit)) {
if (hit.collider.tag == "some_tag") {
// Do something
}
}
}
}
This would be attached to a single game object. The code above uses "Camera.main," to create the ray (the camera tagged as MainCamera), but you can use whatever camera you want. This code uses the "tag" of the game object hit, but you can look for a specific script instead:
Clickable clickable = hit.collider.gameObject.GetComponent(Clickable);
if (clickable != null)
clickable.MyMouseDown()
Before use this, make pretty sure that you have 2 cameras tagged differently. If you have 2 'mainCameras', yes, you need a script to do it.
Your answer
Follow this Question
Related Questions
Camera movement(I have no clue how to code) 0 Answers
Billboarding flat plane with multiple cameras? 2 Answers
How do I move the camera to another object in the scene on mouse down? 1 Answer
Camera Lock 1 Answer
Edit Camera Culling Mask 5 Answers