- Home /
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)
Answer by darthbator · Jun 11, 2014 at 12:03 AM
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
}
Sweet, if that fixed your problem could you please mark it as the correct answer?
This post needs to be more accessible, its the only thing that has worked for me.
I have been searching for 3 hours trying different methods and this is the one that worked for me. Tho I might have been searching for the wrong stuff but I saw similar codes to this but never works. THAN$$anonymous$$ YOU SO $$anonymous$$UCH FOR THIS ANSWER! :D
Your answer
Follow this Question
Related Questions
Touch Not Working 0 Answers
multi touch / swipe issues 5 Answers
Multiple Cars not working 1 Answer
how use specific for mobile button when we have 3 ? 1 Answer