- Home /
Get a mouse object click
Hi,
I have some problem getting the mouse to work, I want to click on an object to turn on/off the game. But I can't is giving me this NullReferenceException: Object reference not set to an instance of an object. I have no idea why, this is just a test. using UnityEngine; using System.Collections;
public class OnOff : MonoBehaviour {
public bool on = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit2D hit = Physics2D.Raycast(Input.mousePosition, Vector2.zero);
if(hit != null) {
if(hit.collider.gameObject.name == "On") {
Debug.Log( "faucet");
}
}
}
}
I'm a beginner, any help? Thanks. Is c#.
Answer by robertbu · Dec 27, 2013 at 04:13 PM
I ran into this issue. I don't know if issue is a bug or if I'm missing something, but a workaround is to check for the existence of the collider as well:
if(hit != null && hit.collider != null)
Note this gets rid of the null reference, but you are not detecting a click. Take a look at Input.GetMouseButtonDown(). You will put your raycast inside of a:
if (Input.GetMouseButttonDown(0)) {
// Existing raycast code goes here
}
The null reference has disappeared, thanks, but the click is not being detected, I have it like this:
using UnityEngine;
using System.Collections;
public class OnOff : $$anonymous$$onoBehaviour {
public bool on = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit2D hit = Physics2D.Raycast(Input.mousePosition, Vector2.zero);
if(hit != null && hit.collider != null) {
if(Input.Get$$anonymous$$ouseButtonDown(0)) {
Debug.Log ("faucet");
}
}
}
}
Why?
Likely issue is that you are not doing the raycast correctly. You need something like:
float dist = transform.position.z - Camera.main.transform.position.z;
var pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
pos = Camera.main.ScreenToWorldPoint(pos);
RaycastHit hit = Physics2d.Raycast(pos, Vector2.zero);
Your answer
Follow this Question
Related Questions
GameObject not detecting collision with floor 0 Answers
Change a specific Gameobjects rigidbody gravity to horizontal (left) 1 Answer
Game Object is moving towards the left when fire button is pressed. 2 Answers
sharedmaterial.fricion behaivior in actual game 0 Answers
How to stop raycast when hitting an object in Unity? 0 Answers