Trigger and raycast error?

Basically im starting an inventory script. I first tried using a raycast, which detects what object its looking through a tag, then returns the name of the gameObject. however, sometimes the ray doesnt pick up the ray. This happens as well while using a trigger. Everything within the code works once the ray can detect the object. The object being detected has a rigidbody component. heres the script:

#pragma strict

var selectedObjectName : String;

var mainCamera : Transform;

var cameraObj : Camera;

var rayDistance : float = 10;

var selectedObject : GameObject;

var rayOn = false;

var guiBackground : Texture;

//GUI positions

var guiX : float = 200;

var guiY : float = 200;

var guiHeight : float = 250;

var guiWidth : float = 250;

function Update () {

var hit : RaycastHit;

var ray = cameraObj.ScreenPointToRay(Vector3(Screen.width/2, Screen.height/2, 0));

Debug.DrawRay(ray.origin, mainCamera.transform.forward * rayDistance, Color.red);

if(Physics.Raycast(ray.origin, ray.direction * 15, hit, rayDistance))
{
	else if(hit.collider == null)
	{
		rayOn = false; // ray is off
	}
	
	if(hit.collider.gameObject.tag == "collectable") // if object with tag collectable is detected
	{
		rayOn = true; //then ray is on  <--- this is for checking whether ray is detecting object or not
		if(Input.GetMouseButtonDown(0))
		{
			selectedObjectName = hit.collider.name;
			Debug.Log("the selected object is called " + hit.collider.name);
			var selectedObject = GameObject.Find(selectedObjectName); // check for string name of current object
			Debug.Log("the actual object is " + selectedObject.name); //check to see if it was changed to gameobject
		}
	}
}

}

var selectedObject = gameObject.Find(selectedObjectName);

Try changing the ‘g’ on gameObject to a capital G. So:

var selectedObject = GameObject.Find(selectedObjectName);

I’ll see if I can spot anything else in the meantime while you try that out.

if(Physics.Raycast(ray.origin, ray.direction * 15, hit, rayDistance))
{
if(hit.collider.gameObject.tag == “collectable”) // if object with tag collectable is detected
{
rayOn = true; //then ray is on <— this is for checking whether ray is detecting object or not
if(Input.GetMouseButtonDown(0))
{
selectedObjectName = hit.collider.name;
Debug.Log("the selected object is called " + hit.collider.name);
var selectedObject = GameObject.Find(selectedObjectName); // check for string name of current object
Debug.Log("the actual object is " + selectedObject.name); //check to see if it was changed to gameobject
}
}
}
else
rayOn = false;

this is what i meant