- Home /
Question by
fir3st0rm9 · Jan 27, 2013 at 02:56 AM ·
gameobjectraycasttagraycasthitnpc
Raycast Based on GameObject Tag
Hi, I'm trying to make a script to talk to NPC's in my game and I want to raycast so that anything that is 3 infront of the player & has the tag "NPC" will talk to the player.
var hit : RaycastHit;
function Update () {
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast(transform.position, fwd,hit,3)&&hit.transform.gameObject.tag == "NPC") {
Debug.Log("NPC");
}
}
When using this code, and I walk up to the NPC, nothing shows in the log. Can you please help to show me where I went wrong?
Thanks!
Comment
Seperate your conditionals in your argument :
if raycast {
then if tagged {
e.g. :
var hit : RaycastHit;
function Update()
{
if ( Physics.Raycast( transform.position, transform.forward, hit, 3 )
{
Debug.Log( "ray hit (tag) : " + hit.collider.gameObject.tag + " : " );
if ( hit.collider.gameObject.tag == "NPC" )
{
Debug.Log("NPC");
}
}
}
Hmmmm... When I walk to the NPC, the console says: ray hit (tag : Untagged :
But the NPC has the tag NPC on it and the console does not log NPC so I am inclined to think that there is something wrong with the second if statement.
if ( hit.transform.gameObject.tag == "NPC" )
{
Debug.Log("NPC");
}
Nope, the Debug doesn't lie.
Your raycast is detecting a collider that is Untagged . Check the tagging of the Colliders of your object.