- Home /
OnMouseDown working only sometimes
I'm very sorry if this question was brought up like a thousand times but being quite new to Unity I didn't manage to find the solution for my problem nor to comprehend what the problem is.
Basically, in a 2d environment I have a group of GameObjects ( cells ) that are sprites with a collider and a script attached to them. I want to detect when the mouse is pressed on each individual cell by using OnMouseDown() method. However, it seems that it works only for some of the cells. And if I move the camera even a bit, some of the cells stop working as well.
So, I have three questions: 1. Am I going the right way? Are there simplier / safer ways? 2. How can I fix it? 3. What is causing the problem?
Code used for this:
public class BasicObject : MonoBehaviour {
void Start() {
createMenu = false;
}
void OnMouseDown() {
createMenu = true;
}
void OnMouseUp() {
createMenu = false;
}
void OnGUI() {
if ( createMenu ) {
GUI.Box( new Rect( 100, 100, 20, 20 ), "Hallelujah" );
}
}
[SerializeField] private string objectName;
private bool createMenu;
}
Picture of what cells are malfunctioning ( red don't work at all, blue don't work after I move camera )
Answer by J0kerPanda · Feb 05, 2017 at 10:10 PM
Okay, so after another day or so I think I figured out approximately what was causing the problem and a workaround.
As you know, working in a 2D space and having a z-axis somewhere still leaves us in a 3D space even though we don't see it all the time. I used z-axis offsets for some sprite rendering stuff I needed and I believe that was causing the problem. Specifics, however, still stays unclear.
The different solution I found was quite simple - Raycasting from Physics 2D from the mouse position to the same point. It will get you the object(s) in the click position.
This is the exact code I'm using to do this.
RaycastHit2D[] hits = Physics2D.RaycastAll( watchCamera_.ScreenToWorldPoint( Input.mousePosition ), new Vector3( 0, 0, 1 ) );
So, my advice would be using OnMouseDown only in simpliest cases because of the unclear nature of when the function works and when it doesn't.
Your answer
Follow this Question
Related Questions
OnMouseDown Firing When I Miss 2DCollider 0 Answers
Character Not Moving RPG Game 0 Answers
Method doesn't work when called in other script 0 Answers
Ray2D from object to mousePos 1 Answer