1
\$\begingroup\$

Im working on a way to check mouse is not over any object on scene to put my object in there. i know i can use OnMouseOver function but i have to add it on all objects script. Is there any other way to check my mouse position is not on any object collider? Its a 2d project. thank you for helping

\$\endgroup\$
2
\$\begingroup\$

An easy way to handle input over a range of gameobject, is to raycast and handle the input yourself.

Consider doing something like this in the Update loop.

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D[] hits = Physics2D.RaycastAll(pos, new Vector2(0, 0), 0.01f);

        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i].collider.tag == "Button")
            {
                 Button button = hits[i].collider.GetComponent<Button>();
                 button.Submit();
            }
        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

You can use 2D RayCast to get the desired effect. In the following example I only have it checking when the user clicks, but I'm sure you can work it out from there.

The trick to checking a single point in 2D is to not give the raycast direction as shown below with vector2.zero

using UnityEngine;
using System.Collections;

public class RayCastPoint : MonoBehaviour 
{
    public Camera MainCamera;

    // Use this for initialization
    void Start () 
    {
        if(MainCamera == null)
            Debug.LogError("No MainCamera");
    }

    // Update is called once per frame
    void FixedUpdate () 
    {
        if(Input.GetMouseButtonDown(0))
        {
            var mouseSelection = CheckForObjectUnderMouse();
            if(mouseSelection == null)
            {
                Debug.Log("nothing selected by mouse");
            }
            else
            {
                Debug.Log(mouseSelection.gameObject);
            }
        }
    }

    private GameObject CheckForObjectUnderMouse()
    {
        Vector2 touchPostion = MainCamera.ScreenToWorldPoint(Input.mousePosition);

        RaycastHit2D hit2D = Physics2D.Raycast(touchPostion, Vector2.zero);

        return hit2D.collider != null ? hit2D.collider.gameObject : null;
    }

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.