- Home /
Unity raycast only sometimes works
I have a raycast script for the axe to hit the tree, it was working absolutely fine 2 days ago. But since yesterday, it only works about 1/10 of the time and i've done nothing to the code.
#pragma strict
var rayLength = 100;
private var treeScript : TreeController;
private var playerAnim : PlayerControl;
function Update()
{
var hit : RaycastHit;
var fwd = transform.TransformDirection(Vector3.forward);
if(Physics.Raycast(transform.position, fwd, hit, rayLength))
{
if(hit.collider.gameObject.tag == "Tree")
{
treeScript = GameObject.Find(hit.collider.gameObject.name).GetComponent(TreeController);
playerAnim = GameObject.Find("FPSArms_Axe@Idle").GetComponent(PlayerControl);
if(Input.GetButtonDown("Fire1") && playerAnim.canSwing == true)
{
Debug.Log("Hit!");
treeScript.treeHealth -= 1;
}
}
}
}
Comment
Try adding Debug.Log(hit.transform.gameObject);
to your raycast to see what it's hitting. It's happened to me before that my Raycast was actually hitting the player's Collider without me realising.
Your answer
![](https://koobas.hobune.stream/wayback/20220612051026im_/https://answers.unity.com/themes/thub/images/avi.jpg)