Unity Raycasting Issue

Hello! (C#) I have in my game first person player, with an empty object on the top (Used as a point from where raycast is used).

I have this script on the point:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class ObjectDetection : MonoBehaviour {


	public float rayDist = 3;
	public Text pickUpText;
	

	void Update()
	{


	    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	    RaycastHit hit;


		if (Physics.Raycast (ray, out hit, rayDist))
		{
			Debug.Log ("hit");
			
			if(hit.collider.gameObject.tag == "test1") 
			{
			pickUpText.text = "Press E to pickup BLAH"; 
				isHit = true;
				Debug.Log("hit");
				//hit.collider.gameObject.GetComponent<MeshRenderer>().enabled = false;
				


			}
			


			//Only For Debug
			if(showHit == true)
			{
			Debug.DrawLine(ray.origin, hit.point);
			Debug.DrawLine(hit.point + (Vector3.up  / 2),hit.point + (Vector3.down / 2),Color.blue);
			Debug.DrawLine(hit.point + (Vector3.left / 2),hit.point + (Vector3.right / 2),Color.red);
			}

		}
		else 
		pickUpText.text = "";
		Debug.Log("not hit");
		


	}


}

So when i play the game:

  • if the ray hits nothing – the console prints “not hit”
  • if the ray hits an object with tag test1 – the console prints “not hit”, “hit”, “not hit”, “hit”, “not hit”, “hit”… and so on "

please tell me WHY?
And how to enable the MeshRender when thy Ray leaves the object??

Thanks!

it’s because you’re ALWAYS printing “not hit” - you need to enclose the lines following the else in braces. as it is right now, the else statement is just for pickUpText.text = "";

easy mistake to make :wink: