Hi everyone,
I’ve been circling around this problem, and I can’t find a solution anywhere.
I basically want to do a raycast2D from a touch, and interact with a button (in this particular case, a sprite, with a collider2D component).
I can get the raycast to work, but IF I don’t hit the button (anywhere else on screen) I always get an error message saying:
“NullReferenceException: Object
reference not set to an instance of an
object Touch_Controls.Update () (at
Assets/Scripts/Touch_Controls.cs:24)”
For some reason, I can’t get the raycast to simply ignore the fact that it’s not hitting anything.
I’m guessing this is probably something very simple I’m just overlooking, but it’s infuriating. Please help me! 
Here’s my code:
using UnityEngine;
using System.Collections;
public class Touch_Controls : MonoBehaviour
{
public GUIText tapText;
public Game_Speed gameSpeedScript;
// Update is called once per frame
void Update ()
{
foreach (Touch touch in Input.touches)
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(touch.position),Vector2.zero);
if (hit.collider.tag == "Button")
{
Debug.Log("Button Activated");
}
else
{
Debug.Log("Nothing hit");
}
}
}
}
Your problem is here:
if (hit.collider.tag == "Button")
When a Raycast() does not hit anything, the collider of the RaycastHit2D will be null. Trying to get ‘.tag’ from a null collider will generate the exception. Change the line to something like:
if ((hit.collider != null) && (hit.collider.tag == "Button))
you must check if the hit.collider is not null first:
if (hit.collider != null && hit.collider.tag == "Button"){
Debug.Log("Button Activated");
}
you can check the usage of Physics2D.Raycast here: