- Home /
Using raycast and collider to increase int
I looked at the raycast documentation script on the unity website to try and understand raycasts. I was using the script and was wondering how i can change it to make the raycast know if it hit a certain collider then increase an int by 1 if it hit the correct collider. (the code sample button isnt working properly so i have to insert the code here)
//
//
using UnityEngine; using System.Collections;
public class Raycast : MonoBehaviour {
public float RayDistance = 5;
void Update() {
if (Input.GetButtonDown ("Fire1"))
{
Vector3 fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, RayDistance))
print ("There is something in front of the object!");
}
}
}
Answer by Tomer-Barkan · Jul 04, 2015 at 05:28 AM
You need to assign the result of the raycast into a RaycastHit, there you have a reference to the collider that was hit, and from it you can get any component of that object and check it's tag, name, or anything else you want.
RaycastHit hitInfo;
if (Physics.Raycast (transform.position, fwd, out hitInfo, RayDistance)) {
GameObject hitObject = hitInfo.collider.gameObject;
if (hitObject.tag == "sometag") {
// Do something
}
}
I tried that but its not increasing the int
using UnityEngine;
using System.Collections;
public class ResourcesGather : $$anonymous$$onoBehaviour {
public float RayDistance = 5;
public RaycastHit hitInfo;
//RESOURCE TYPES
public int Wood = 0;
void Update() {
if (Input.GetButtonDown ("Fire1"))
{
Vector3 fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, out hitInfo, RayDistance))
{
print ("There is something in front of the object!");
GameObject hitObject = hitInfo.collider.gameObject;
if (hitObject.tag == "Tree")
{
print("You hit a tree, have some wood");
Wood += 1;
}
}
}
}
}
I'm only seeing the message "There is something in front of the object!" I'm not seeing the message "you hit a tree, have some wood" and the int isn't increasing either. Any ideas?
Debug to identify what you hit :
print ("There is something in front of the object! name = " + hitInfo.collider.gameObject.name + ". tag = " + hitInfo.collider.gameObject.tag );
Please note if you are trying to raycast a tree that is painted on the terrain, it will not show as tree but terrain. Painted tree colliders become part of the terrain collider.
http://answers.unity3d.com/questions/685405/mass-place-trees-tagging.html
http://answers.unity3d.com/questions/650308/how-do-i-interact-with-terrain-trees.html