- Home /
how to detect a mouse click that happened but wasnt on the gameobject?
Is there a way to detect a mouse click input and do something but only if the click was somewhere other than the gameobject? so its checking if the mouse was clicked but the gameobject was clicked? then do something. For example shoot if mouse is clicked anywhere but dont shoot if mouse is clicked on gameobject.
Answer by Positive7 · Jul 18, 2015 at 11:10 PM
using UnityEngine; using System.Collections;
public class Tester : MonoBehaviour { public bool shotEnabled;
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100f)) {
if (Input.GetMouseButtonDown (0)) {
if (hit.transform.name == "Cube") {
shotEnabled = false;
} else {
shotEnabled = true;
}
}
}
}
}
Answer by PDay · Jul 20, 2015 at 05:03 PM
This should do as you want. It works on a simple cube object with collider. You'll want to change the two Debug.Log lines to a function you want to call in the instances where it is hit or missed:
public class MissScript : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit) && this.gameObject.Equals(hit.transform.gameObject)) Debug.Log ("Hit");
else Debug.Log ("Miss");
}
}
}
This works for a 3D gameobject, how do i get it to work for a 2D box collider because when i click on the 2d box collider i get a miss
I replaced Physics with Physics2D in the if statement but i just get an error. How do i change the script to match a 2D collider
void Update () {
Vector3 screenPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
if(Physics2D.Raycast(screenPos, Vector2.zero) && hit.collider.name == "Cube"){
Debug.Log ("Hit");
}else{
Debug.Log ("$$anonymous$$iss");
}
}
}