Problem with picking up objects using a raycast and placing them in the inventory.

Hi there,

So I made two scripts both attached to a different gameobject. I tried to get an input from the user and then draw a line to the item. If the item would be in a certain range i’d add the item to the inventory and then destroy the item from the world so it would be placed inside my inventory.

The problem is that whenever I walk up to an item and pick it up every other item is automaticlly also picked up. But I only want it to pick up that one item I was looking at.

This is my script:

#pragma strict

private var _inventoryScript : Inventory;
private var _player : GameObject;

var maxDistance : float = 2;

function Start()
	_player = GameObject.FindGameObjectWithTag("Player");
	_inventoryScript = _player.GetComponent(Inventory);

function Update()
		var hit : RaycastHit;
		var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5, 0));
		if(Physics.Raycast(ray, hit, maxDistance))
			if(hit.collider.gameObject.tag == "Item")

This script is the same for every item all I did was change the number in the AddItem function when i’m calling it to a certain item ID.

How can I make it so that when I try to pick up the item it doesn’t place all the other items in my inventory aswell?

Assuming this is on every item, you can change line 23 to:

 if (hit.transform == transform)

Note it would be better to only have this script on one game object. Then rather than the change I just outlined, you could change line 26 instead:


And therefore you would only have a single Raycast() rather than a Raycast() by every item in the scene.