- Home /
Detect tag with 2d raycasting
So I am making a pokemon clone in unity. For this project I need to know if you can walk somewhere. I don't want to use box colliders since it looks buggy.
So I have got this so far:
if (Input.GetKey(KeyCode.UpArrow) && isMoving == false)
{
bool disableMove = false;
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.up, 0.1F);
if (hit != null)
{
if (hit.collider.gameObject.tag == "collision")
{
disableMove = true;
}
}
if (!disableMove)
{
increment = 0;
isMoving = true;
startPoint = transform.position;
endPoint = new Vector2(transform.position.x, transform.position.y + 1);
}
disableMove = false;
}
this gives me a Nullreference on
if (hit.collider.gameObject.tag == "collision")
I am not sure how to solve this. what am I missing?
If you have any idea just post it. I really do need to fix this issue because at this point it's blocking my development.
Add debug right after hit!= null to print hit.name; I don't know how it would not be null yet return null ref on that but maybe a debug will show 'something' in hit.name
@getyour411 there is no hit.name I have no idea how it gets past my check and then throws a nullreference.
And it does stop me from walking however not when im one tile away from the border but entirely im not able to move up anymore.
allright so it gives me as a warning: Assets/Player$$anonymous$$ovement.cs(39,17): warning CS0472: The result of comparing value type "UnityEngine.RaycastHit2D" with null is "true" which means my hit is not null. But why am I getting a nullpointer?
This bug has come up a number of times. I'm not sure what situations produce it or if it is by by design, but the common fix is to change line 8 to:
if (hit.collider != null && hit.collider.gameObject.tag == "collision")
Answer by lol_lol_lol · Apr 26, 2014 at 12:51 AM
So i fixed it myself...
I stopped using a tag and made a new layer called it collision. then I changed this:
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.up, 0.1F);
if (hit != null)
{
if (hit.collider.gameObject.tag == "collision")
{
disableMove = true;
}
}
to this:
public LayerMask GroundLayer;
if (Physics2D.Raycast(transform.position, Vector2.up, 1, GroundLayer))
{
disableMove = true;
}
else
{
Debug.Log("nothing");
}
just give your gameObject a layer select the layer on your script. Then it will work!
Your answer
![](https://koobas.hobune.stream/wayback/20220613143609im_/https://answers.unity.com/themes/thub/images/avi.jpg)