Hello
I have ran into a scripting issue and was wondering if anyone can give me some insight as to how to fix my script. What I am trying to do is use the below script to raycast to an object with a specific tag, Food in this case. Although I am unable to get the conditional if statement to work. The object I am using for the test is an object that I imported from maya in fbx format and assigned a mesh collider and the Food tag to. The script is being ran though a camera pointed at the object. So far when executed the script defaults to printing “not working” within the console. Thanks in advance for any help that is given.
var vacRange = 30.0;
function Update() {
if (Input.GetKeyDown(KeyCode.E)){
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit, vacRange)) {
print(“hit something”);
if(hit.collider.gameObject.tag==“Food”){
print(“hitting food”);
}else{
print(“not working”);
}
}
}
}
Isolate your bug:
var vacRange = 30.0;
function Update() {
if (Input.GetKeyDown(KeyCode.E)) {
var hit: RaycastHit;
if (Physics.Raycast(transform.position, transform.forward, hit, vacRange)) {
print("hit something: " +hit.collider.gameObject.tag );
if (hit.collider.gameObject.tag == "Food") {
print("hitting food");
} else {
print("not working");
}
}
}
}
First of all, use hit.transform.tag and not hit.collider.gameObject.tag. Faster this way.
Second, imported models usually come with an empty parent object. Make sure your mesh collider actually does cover the entire surface of the model and not just the empty parent gameObject of the imported model.
Third, make sure that your camera’s pivot is oriented properly. I see no reason why it shouldn’t be, but if your camera’s Z axis isn’t facing forward, its transform.forward will not be actually forward.
Other than that I see nothing wrong with your code.
Thanks for the input, I was able to find out that the script is functioning, just not with the objects that I import. Is there a specific way I should be exporting my files to avoid invisible parents and how would one check if the collider covers the entire mesh? I typically use mesh collider with most of what I import into unity. Should I change my workflow to something different?
Just figured it out when looking over my maya file. Didn’t take into account the extra camera views that are present within the outliner and since I was just exporting all it must have created the extra game objects.
You can always detatch the children. As for the Collider, you shouldn’t be using Mesh Colliders if you care about performance. Work with sphere and box colliders instead, and if you want to be accurate, use multiple sphere and box colliders on an object instead of a mesh collider - it will still be faster.
As for how you can tell if an object’s collider covers the entire object or not, Colliders are depicted as a green outline in your scene view.