- Home /
RaycastHit collider not showing correct tags
So I been trying to make a gun using Physics.Raycast and up until now it has seemed perfect. But now I'm trying to use tags so that whenever you shoot something it gets destroyed, and the collider doesn't seem to be showing the right tags.
Here's my code:
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
Instantiate(hitEffect, hit.point, Quaternion.Euler(Vector3.zero)));
Debug.Log("Tag: " + hit.collider.gameObject.tag);
if(hit.collider.gameObject.CompareTag("Enemy"))
Destroy(hit.collider.gameObject);
}
I've tried several variations like hit.collider.tag and hit.collider.gameObject.tag == "Enemy", but still no luck. I'm using Unity 4.
What does your Debug.Log()
show when you hit something?
I don't think I see any problem with your code, but could you try
Debug.DrawLine( Vector3.Lerp( transform.position, hit.point, 0.5f), hit.point );
This will draw a line from the hit object and point back to the gameObject you attached this script to, just to double confirm that the raycast is working properly.
It says "Untagged" no matter what I hit. I have a separate gun that fires grenades and uses OnCollisionEnter(Collision c) to handle collisions with the grenades, and it works properly with tags so I know I have them set up right.
Because I do not know how you setup your scene, the only advice I can give you know is to setup a super basic scene with a short script from scratch to make sure whether if the raycast/colliders are setup correctly.
Even though you have said that I have a separate gun that fires grenades and uses OnCollisionEnter(Collision c) to handle collisions with the grenades, and it works properly with tags, I will still advice you to run a fresh scene just to make sure that you did not missed out anything.
Answer by crazymonkay · Apr 08, 2013 at 04:05 AM
Alright, apparently it was the simplest thing that was causing my issue, haha. I somehow got 2 box colliders on my prefab, and it was hitting the one that was untagged. Thanks for your help anyway!