- Home /
Rays and tags help?
Here's my code for a raycast. I need help.
using UnityEngine;
using System.Collections;
public class RaycastScript : MonoBehaviour {
RaycastHit hit;
// Use this for initialization void Start () {
}
// Update is called once per frame void Update () {
if(Input.GetButtonDown("Fire1")) {
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 10000, Color.blue);
if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), 100000000)) {
Debug.Log ("you hit something");
} }
} }
I want to make it so that if the ray hits an object with the "Cube" tag, it sends a message to the debug.log that says "you hit a cube". Would I do:
if (hit.collider.gameobject.tag == "Cube") { debug.log("you hit a cube"); }
Or something else?
I use C#, btw
Answer by Apples_mmmmmmmm · Jul 31, 2012 at 06:26 AM
your current ray is using the method overload for (origin, direction, distance). If you want to return data about a tag you need to use a method overload that contains 'out hitinfo'.
For example:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit))
float distanceToGround = hit.distance;
}
}
With this data, you could then use your if statement to determine if the object contained the tag you need.
Your answer
![](https://koobas.hobune.stream/wayback/20220613074941im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Raycasting and Tag Checking in C#? 1 Answer
Raycast on touch 3 Answers
Distribute terrain in zones 3 Answers