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");
}
}
}
}