How can I use hit.gameObject.tag?

How can I use the hit.gameObject.tag by using JS?

Can anyone help me? I am a starter.

As you probably already know you can get hit information from a Raycast sending a RaycastHit along with your Raycast. The RaycastHit is a struct which holds information if the Raycast has hit a collider in the scene. The struct holds references to the components of collider, rigidbody and transform, but not GameObject. Tag, which is a way of sorting/dividing certain objects from another, however do derive from the components collider, rigidbody and transform.

So the quick answer is, you don’t use hit.gameObject.tag, you can however use hit.collider.tag which is a string.

From the Inspector of a selected GameObject you can set the tag name. As just described you do this to group together certain objects. For instance, when interacting with objects, you might only be interested to return a certain type that has a special tag, or searching for a group of objects with a certain tag, using FindGameObjectsWithTag(“Tag name”).

Here is an example of using a RaycastHit and comparing a tag:

function Start () {
   var hit : RaycastHit = InteractionRaycast(Camera.main, Input.mousePosition);
    if (hit.collider) {
        // The hit has a collider, now check its tag
        if (hit.collider.tag=="My Fantastic Tag Name") {
            Debug.Log(hit.collider.name+" has my fantastic tag name!");
        }
    }
}

function InteractionRaycast (cam : Camera, pos : Vector2) : RaycastHit {
	var hit : RaycastHit;
	var ray : Ray = cam.ScreenPointToRay(pos);
	Physics.Raycast(ray, hit, 100);
	return hit;
}

Did this answer your question? If not, how do you want to use the returning tag from a hit?