2D Raycast touch

I’m trying to cast a raycast from wherever I touch on the screen. If that object tag is equal to “Player”, I want it to run my code but as soon as I hit anything other than Player, I receive an error.

Can someone shed some light on this?

void Cast()																																		
        {
            for (int i = 0; i < Input.touchCount; ++i)
            {
                Vector2 test = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
                if (Input.GetTouch(i).phase == TouchPhase.Stationary)
                {
                    test = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
                    
                    if(Physics2D.Raycast(test, (Input.GetTouch(i).position)).collider.tag == "Player")
                    {
                        Debug.Log("yup");
                    }
		        }
	       }
	   }

Here’s my error NullReferenceException: Object reference not set to an instance of an object
PlayerControl.Cast () (at assets/Scripts/PlayerControl.cs:170)
PlayerControl.FixedUpdate () (at assets/Scripts/PlayerControl.cs:153)

If you don’t hit anything and get a null collider you’re going to see this NRE behavior. That’s because you’re trying to inspect an object that has not been assigned (collider). Collider is only populated when a ray actually hits. No matter what happens in a 2D raycast you get back a RaycastHit2D object. If you hit nothing the collider field is not assigned.

Unless you want to write your own 2d touch detection that returns bools (which is what I will normally do) You’ll want to populate a variable with the return and then check that for value before you check against it.

RaycastHit2D hit = Physics2D.Raycast(test, (Input.GetTouch(i).position);
if (hit.collider && hit.collider.tag == "Player"){
//do stuff
}