OnMouseDown not triggering

OnMouseDown() isn’t working for me.
Here’s some info related to things I’ve read could cause this problem.

  • I have two cameras (one renders to a
    target texture, the other acts as the
    main camera)
  • Both are orthographic.
  • Their clipping planes are not negative
  • Their z is -100
  • I have things I’m trying to click
  • They have BoxCollider2Ds.
  • They are the only things with
    colliders, so there should be
    shouldn’t be any colliders between
    them and the camera.
  • Their z is 30

Ok, are those objects with coliders children of someone? I had problems once with coliders of children of a parent with collider

Turns out my problem was because of some things I did when following Pushy Pixel’s Pixel Perfect tutorial that basically resulted in camera/screen things being slightly wonky – and by extension, the mouse. My solution was to create a custom mouse object, and then using its location henceforth. I also had to use a Box Collider instead of a Box Collider 2D.

Attach this to your mouse object. CharController is just the object I wanted to click on, and MouseEnter, MouseDrag, etc, are custom functions within that object

`

CharController lastChar;
CharController currentChar;
Vector3 lastPosition;  // Where the mouse position was last
const int z = 0;

void Start()
{
    MoveMouse();
    Cursor.visible = false; // hide OS cursor
    lastPosition = Input.mousePosition;
}

void Update()
{
    CheckMouse();
    Vector3 mousePos = Input.mousePosition;
    // If the mouse has moved since the last update
    if (mousePos != lastPosition)
    {
        lastPosition = mousePos;
        MoveMouse();
    }
}

void MoveMouse()
{
    Vector3 tempPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    tempPos.z = z; // preserve z
    transform.position = tempPos;
}

public void CheckMouse()
{
    Ray ray = new Ray (transform.position, new Vector3(0, 0, GlobConsts.maxDepth)); // ray from mouse directly downwards
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        currentChar = hit.collider.GetComponent<CharController>();
        if (currentChar != lastChar)
            currentChar.MouseEnter();
        if (Input.GetMouseButton(0))
            currentChar.MouseDrag();
        if (Input.GetMouseButtonDown(0))
            currentChar.MouseDown();
        if (Input.GetMouseButtonUp(0))
            currentChar.MouseUp();

        lastChar = currentChar;

    }
    else if(lastChar != null)
    {
        currentChar.MouseExit();
        lastChar = null;
    }
}

`