- Home /
RaycastHit2D not interacting with tags
I've been hacking my way through references and other questions, but I haven't stumbled upon an answer that has helped a whole ton. I've tried to create a ray that projects from the position of the mouse, and that ray is supposed to 'pick up' any tags that it collides with. On line 19 (not including the part that wasn't transmitted into the code), it says "NullReferenceException: Object reference not set to an instance of an object" and I'm quite new to unity, so I'm not entirely sure how to interpret this... If anyone could help with my little blip, that would be greatly appreciated!
using UnityEngine; using System.Collections;
public class MousePosition : MonoBehaviour {
private Vector2 ScreenPosition;
public bool MouseOnTent = false;
void Start () {
}
void Update () {
MouseInteraction ();
}
void MouseInteraction() {
ScreenPosition = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
RaycastHit2D hit = Physics2D.Raycast (ScreenPosition, Vector2.zero);
//Creates a ray that detects if it is hitting a tag where the mouse is
if (hit != null) {
if (hit.transform.tag == "Tent")
MouseOnTent = true;
}
else {
MouseOnTent = false;
}
}
}
Answer by robertbu · Oct 29, 2014 at 03:03 AM
For future questions please format your code. After pasting, select your code and use the 101/010 button. Also for future questions include the full text of the error message from the console. Without these two, I'm left guessing about the error. I'll be it is this line:
ScreenPosition = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
'camera' will refer to any camera on the same game object with this script. If this script is not attached to a camera, you'll get a null reference exception. You may want to replace 'camera' with 'Camera.main'. 'Camera.main' will be the camera in the scene with the tag 'MainCamera', so it too will fail if you change the tag on the default camera Unity puts in a scene.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Strange Problem: NullReferenceException 2 Answers
Distribute terrain in zones 3 Answers