- Home /
Raycast isn't working when with tag
If I add "&& Hit.collider.tag" part to my function it wouldn't work, I check if the object desired is properly tagged and it was.
void Raycast()
{
RaycastHit2D Hit = Physics2D.Raycast (transform.position, Vector2.down );
if (Hit.distance < 0.9f && Hit.collider.tag == "ground")
{
Debug.Log("dd");
}
}
First of all, use Hit.collider.CompareTag("ground")
ins$$anonymous$$d of string comparison. Then, are you sure the tag is exactly named ground
(and not Ground
for example?)
Have you tried to do a simple tag / name check :
if (Hit.distance < 0.9f )
{
Debug.Log(Hit.collider.tag);
}
Something may be hit before the ground.
By extension, you could try
Debug.Log(Hit.gameObject.name + ": tag = " + Hit.collider.tag + " -- distance = " + Hit.distance);
to verify what you hit and how far away it is.
Answer by smoky_gamer · Oct 12, 2017 at 03:12 PM
hey, 1.do you set the tag to your ground gameobject. 2.i think if you check the hit.collider.gameobject.tag == "ground" your problem will be fixed 3.maybe you doesnt attach collider to the gameobject 4.if your problem doesnt fix try check with layer instead of tag (the code is below) //the third parameter is the distance from ground , the forth parameter is the layer of ground (you have to attach ground layer to ground gameobject instead of tag.
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.5f, LayerMask.GetMask("ground"));
if (hit.collider != null)
{
}
Answer by msafa · Oct 12, 2017 at 11:01 AM
Can you try this
Hit.transform.tag.Equals("ground")
instead of Hit.collider.tag == "ground"
can you check your tag name with debug.log function?
Debug.Log(Hit.transform.tag);