Raycasting to pick up an item problem

Hello! I am having an issue with raycasting and picking up an item: my code only gets to “a!” in the console, and then throws an error. Physics.Raycast is supposed to take in a Vector3 origin, Vector3 direction, and a float maxDistance, but it does not accept my “out hit” as a direction. I’ve also tried ray.direction as the direction, but it still does not work. Can someone please point me in the right direction of what I’m doing wrong here? :slight_smile:

using UnityEngine;
using System.Collections;

public class ItemPickup : MonoBehaviour {

	private InventoryScript inventory;
	public float raycastLength = 5f;

	void Start () {
		inventory = GameObject.FindGameObjectWithTag("InventorySystem").GetComponent<InventoryScript>();
	}

	void Update () {
		// Create variables for the ray and the possible hit.
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		Debug.Log("a!");

		if (Physics.Raycast(ray, out hit, raycastLength)) //PROBLEM LIES HERE
		{
			Debug.Log("b!");
			// We hit something! Check if we can pick it up.
			if (hit.collider.gameObject.tag == "Pickupable")
			{
				Debug.Log("Found item!");
				if (Input.GetKeyDown("e"))
				{
					// Add the item to the inventory and destroy it in the world.
					inventory.item++;
					Destroy(hit.collider.gameObject);
				}
			}
		}
	}
}

Tested your script, there’s no problem in my case. Prints a! and b!.

Try once my pickup script, that is working very well and is almost the same (take out the InvWindow check)…

using UnityEngine;
using System.Collections;

public class Focus : MonoBehaviour {

    private GameObject InvWindow;
    private LayerMask Mask = 1;
    public RaycastHit Hit;
    public GameObject Item;

    void Awake()
    {
        InvWindow = GameObject.Find("InvWindow");
    }  

    void Update()
    {        
        if (Physics.Raycast(transform.position, transform.forward, out Hit, 10.0f, Mask.value))
        {
            Item = Hit.collider.gameObject;            
            if (Hit.distance <= 1.5f && InvWindow.active == false)
            {
                Item.SendMessage("PickUp", true, SendMessageOptions.DontRequireReceiver);
            }
        } 
    }

}